今天上午训练赛,果断水过,一道题都没有成功AC,惭愧,不发题解了。还是安静地看看基础。学学Nimm博弈。
Nimm Game
传说中的博弈论入门题目。
首先有几个概念:
奇异
用(a,b,c)表示某种局势,首先(0,0,0)显然是奇异局势,无论谁面对奇异局势,都必然失败。第二种奇异局势是(0,n,n),只要与对手拿走一样多的物品,最后都将导致(0,0,0)。仔细分析一下,(1,2,3)也是奇异局势,无论对手如何拿,接下来都可以变为(0,n,n)的情形。
局势转换
从一个非奇异局势向一个奇异局势转换的方式可以是:
1)使 a = c xor b;
2)使 b = a xor c;
3)使 c = a xor b.
至于为什么?尼姆博弈的数学理论-Wiki
例
例1 (14,21,39),14(+)21=27,39-27=12,所以从39中拿走12个物体即可达到奇异局势(14,21,27)。
例2 (55,81,121),55(+)81=102,121-102=19,所以从121中拿走19个物品就形成了奇异局势(55,81,102)。
例3 (29,45,58),29(+)45=48,58-48=10,从58中拿走10个,变为(29,45,48)。
Game Play:original(7,8,9)
甲:(7,8,9)->(1,8,9)奇异局势
乙:(1,8,9)->(1,8,4)
甲:(1,8,4)->(1,5,4)奇异局势
乙:(1,5,4)->(1,4,4)
甲:(1,4,4)->(0,4,4)奇异局势
乙:(0,4,4)->(0,4,2)
甲:(0.4,2)->(0,2,2)奇异局势
乙:(0,2,2)->(0,2,1)
甲:(0,2,1)->(0,1,1)奇异局势
乙:(0,1,1)->(0,1,0)
甲:(0,1,0)->(0,0,0)奇异局势
甲胜。
接下来看看OJ题:
POJ 2234
Description
Here is a simple game. In this game, there are several piles of matches and two players. The two player play in turn. In each turn, one can choose a pile and take away arbitrary number of matches from the pile (Of course the number of matches, which is taken away, cannot be zero and cannot be larger than the number of matches in the chosen pile). If after a player’s turn, there is no match left, the player is the winner. Suppose that the two players are all very clear. Your job is to tell whether the player who plays first can win the game or not.
Input
The input consists of several lines, and in each line there is a test case. At the beginning of a line, there is an integer M (1 <= M <=20), which is the number of piles. Then comes M positive integers, which are not larger than 10000000. These M integers represent the number of matches in each pile.
Output
For each test case, output “Yes” in a single line, if the player who play first will win, otherwise output “No”.
Sample Input
2 45 45
3 3 6 9
Sample Output
No
Yes
给出M个Nimm堆,问先手是否得胜。
#include <cstdio>
using namespace std;
int main(){
int m,ans,n;
while(~scanf("%d",&m)){
n=ans=0;
scanf("%d",&n),ans^=n;
//printf("ans=%d\n",ans);
if(ans)printf("Yes\n");
else printf("No\n");
}
}
不断读取新数进行异或操作,最后结果为0则先手不胜,不为0则先手胜利。