Revenge of Nim
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 721 Accepted Submission(s): 370
---Wikipedia
Today, Nim takes revenge on you. The rule of the game has changed a little: the player must remove the objects from the current head(first) heap. Only the current head heap is empty can the player start to remove from the new head heap. As usual, the player who takes the last object wins.
Each test case begins with an integer N, indicating the number of heaps. Then N integer Ai follows, indicating the number of each heap successively, and the player must take objects in this order, from the first to the last.
[Technical Specification]
1. 1 <= T <= 100
2. 1 <= N <= 1 000
3. 1 <= Ai <= 1 000 000 000
2 1 2 2 1 1
Yes No
4994解题思路
题目翻译:
问题描述:
取物游戏(Nim)是一个关于战略问题的数学游戏。在这个游戏中两个玩家轮流将物体从不同的堆中取出。每个回合,玩家必须删除至少一个物体,可以删除来自同一个堆的任意数量的物体。
今天,Nim对你实施报复。游戏的规则已经改变了一点:玩家必须把物体从当前头堆(第一个堆)取出。只有当前头堆是空的时,玩家才可以开始删除新头堆。像往常一样, 将最后一个物体取出的玩家获胜。
输入:
第一行包含一个整数,表示测试用例的数量。
每个测试用例始于一个整数N,指示堆的数量。紧跟着是N个整数Ai,相继表示每个堆的数量,玩家必须按此顺序来取物体,从第一个到最后一个。
输出:
对于每个测试组,如果第一个玩家总能赢输出“Yes”,否则输出“No”
样值输入:
2
1
2
2
1 1
样值输出:
Yes
No
思考:
列举几种情况如下:
N | 1 | 2 | 2 | 3 | 3 | 3 | 3 | ||||||||||
Ai | m | 1 | m | n | m | 1 | 1 | m | 1 | n | m | n | 1 | m | n | n | m |
r | yes | no | yes | yes | no | yes | yes |
n | 4 | 4 | 4 | 4 | 4 | 4 | 4 | 4 | |||||||||||||||||||||||||
a | 1 | 1 | 1 | M | 1 | 1 | n | M | 1 | n | 1 | M | n | 1 | 1 | M | 1 | n | n | M | n | 1 | n | M | n | n | 1 | M | n | n | n | M | |
r | No | Yes | no | Yes | No | Yes | Yes | yes |
5 | 5 | 5 | 5 | 5 | 5 | 5 | 5 | ||||||||||||||||||||||||||||||||
1 | 1 | 1 | 1 | M | 1 | 1 | 1 | N | M | 1 | 1 | N | 1 | M | 1 | 1 | N | N | M | 1 | N | 1 | 1 | M | 1 | N | 1 | N | M | 1 | N | N | 1 | M | 1 | N | N | N | M |
Yes | No | Yes | Yes | No | No | No | No | ||||||||||||||||||||||||||||||||
5 | 5 | 5 | 5 | 5 | 5 | 5 | 5 | ||||||||||||||||||||||||||||||||
N | 1 | 1 | 1 | M | N | 1 | 1 | N | M | N | 1 | N | 1 | M | N | 1 | N | N | M | N | N | 1 | 1 | M | N | N | 1 | N | M | N | N | N | 1 | M | N | N | N | N | M |
Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
只要第一个拿的人能掌握主动权,那他就可以赢。总结上述规律可以发现只要前几个连续的“1”的个数是偶数个,那么第一个拿取的人就占有主动权,就可以赢。用这个规律来解决问题就非常简单了。
代码:
#include <iostream>
using namespace std;
int main()
{
int T,N,count,i,j;
int A[1000];
cin >> T;
for(i=1;i<=T;i++)
{
cin >> N;
for(j=1;j<=N;j++)
{
cin >> A[j];
}
count=0;
for(j=1;j<N;j++)
{
if(A[j]==1)
count++;
else
break;
}
if(count%2==0)
cout << "Yes" <<endl;
else
cout << "No" <<endl;
}
return 0;
}
祝大家好运!