2014-04-30 16:12
原题:
The beauty of a number X is the number of 1s in the binary representation of X. Two players are plaing a game. There is number n written on a black board. The game is played as following: Each time a player chooses an integer number (0 <= k) so that 2^k is less than n and (n-2^k) has as beautiful as n. Next he removes n from blackboard and writes n-2^k instead. The player that can not continue the game (there is no such k that satisfies the constrains) looses the game. The First player starts the game and they play in turns alternatively. Knowing that both two players play optimally you have to specify the winner. Input: First line of the Input contains an integer T, the number of testcase. 0 <= T <= 5. Then follow T lines, each containing an integer n. n more than 0 and less than 10^9 +1. Output For each testcase print "First Player" if first player can win the game and "Second Player" otherwise. Sample Input 7 1 2 8 16 42 1000 123 Sample Output Second Player First Player First Player Second Player Second Player First Player Second Player Explanation In the first example n is 1 and first player can't change it so the winner is the second player. In the second example n is 2, so the first player subtracts 1 (2^0) from n and the second player looses the game.
题目:两人玩一个数字游戏,开始在黑板上写一个正整数。两人轮流对该数执行一种操作:将这个数换成一个更小的正整数,但得保证变化之后的数在二进制表示里具有相同个数的‘1’。比如5变到3就满足条件,两者的二进制里都有两个‘1’。如果轮到某人时,无法找到更小且满足条件的数,则此人输掉游戏。给定一个初始的数字n,请判断在双方都最优策略的情况下,谁一定会赢?有必胜策略吗?
解法:从题目里看这就像个博弈的题,于是我在错误的思路下进行了第一次尝试,最终明白这题似乎不用博弈。用一个例子来观察这种游戏规则:“100110”,这个数可以变成“10110”、“100101”。可以发现都是在“10”的地方变成了“01”,也就是把其中一个“1”向右移动一位。那么游戏何时结束?到了“111”就结束了,因为没有多余的“0”可供移动了。起点和终点都清楚了,并且每次只能移动一位,所以游戏的回合数其实是固定的,根据这个回合数的奇偶就知道谁输谁赢了。算法可以在O(log(n))时间内完成。
代码:
1 // http://www.careercup.com/question?id=5110993575215104 2 #include <cstdio> 3 using namespace std; 4 5 int main() 6 { 7 int nzero; 8 int sum; 9 int n; 10 11 while (scanf("%d", &n) == 1 && n > 0) { 12 sum = 0; 13 nzero = 0; 14 while (n > 0) { 15 if (n & 1) { 16 sum += nzero; 17 } else { 18 ++nzero; 19 } 20 n >>= 1; 21 } 22 printf((sum & 1) ? "First player wins.\n" : "Second player wins.\n"); 23 } 24 25 return 0; 26 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)