HDU 4994 Revenge of Nim(博弈)

来源:互联网 发布:java多线程与并发视频 编辑:程序博客网 时间:2024/05/16 07:26

Revenge of Nim

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 0    Accepted Submission(s): 0


Problem Description
Nim is a mathematical game of strategy in which two players take turns removing objects from distinct heaps. On each turn, a player must remove at least one object, and may remove any number of objects provided they all come from the same heap.
---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.
 

Input
The first line contains a single integer T, indicating the number of test cases. 

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
 

Output
For each test case, output “Yes” if the first player can always win, otherwise “No”.
 

Sample Input
21221 1
 

Sample Output
YesNo
 

Source
BestCoder Round #9
 

题目大意:有n堆石子,每堆有ai个,每次按照堆的先后顺序至少取走一个石子,如果先手最后取完石子,输出Yes,否则,输出No。



解题思路:如果每堆石子的数目都大于1,则先手在取前n-1堆石子时,每次都留下一个石子,在取最后一堆时,一次取完,则先手必赢,这是先手的必胜态,但是如果有些堆的石子数不大于1时,当每出现一个大于1的石子堆时,对于取该堆石子的人,他有两种取法,一是全部取走,二是取走ai-1个(即留下1个),而这两种方式在不同的情况中可以使用其中一种使得自己处于必胜态。因此只要判断出从前往后的前n-1堆中,谁先取得第一堆数目大于1的石子堆的主动权,谁就是赢者。因此只需要求出第一堆数目大于1的石子堆前有多少个1就可以判断了,如果有偶数个1, 则先手赢,如果有奇数个1,则先手输。



代码如下:

#include <cstdio>#include <cstdlib>#include <cstring>#include <cmath>#include <ctime>#include <iostream>#include <algorithm>#include <string>#include <vector>#include <deque>#include <list>#include <set>#include <map>#include <stack>#include <queue>#include <numeric>#include <iomanip>#include <bitset>#include <sstream>#include <fstream>#include <limits.h>#define debug "output for debug\n"#define pi (acos(-1.0))#define eps (1e-6)#define inf (1<<28)#define sqr(x) (x) * (x)#define mod 1000000007using namespace std;typedef long long ll;typedef unsigned long long ULL;int main(){    int i,j,k,n,t,sum;    int a[1005];    scanf("%d",&t);    while(t--)    {        scanf("%d",&n);        for(i=0;i<n;i++)            scanf("%d",&a[i]);        sum=0;        for(i=0;i<n-1;i++)        {            if(a[i]==1)                sum++;            else                break;        }        if(sum%2==0)            printf("Yes\n");        else            printf("No\n");    }    return 0;}


0 0
原创粉丝点击