poj 2234基础Nim博弈||sg博弈

来源:互联网 发布:义乌美工培训多少钱 编辑:程序博客网 时间:2024/06/05 03:59

poj 终于突破200大关了,mark一下。hdu也快要300了。加油

http://poj.org/problem?id=2234

题意:

有n堆石子,每人每次可以从一堆中拿走任意多个,两人轮流操作,谁无子可取谁输。输入n堆石子各自的数量,输出先手是否能赢。

分析:NP问题,必胜态N(next player wins),必败态P(previous player wins)

如果某状态的直接后继中有必败态那么它一定是必胜态,否则为必败态。

SG函数。设函数g(x)。我们先把所有的最终局面(最终局面均为必败P局面)g(x)赋值为0。然后所有其他局面g(x)等于其直接后继状态中没有出现过的最小自然数。这样一来所有是g(x)=0的状态就是必败态,其他为必胜态。

根据定理:有这样一个游戏,是多个游戏共同进行,每个游戏都执行到底时才算整个游戏结束,每次一个选手可以把一个游戏进行一步。对于这样的游戏它的某状态的g(x)值,为每个子游戏的现在所处的状态的g(x)值抑或起来的结果。

所以对于本题,我们只需要研究一堆石子的g(x)的规律即可得出若干堆石子共同进行的胜败。

对于一个有n个石子的堆,其开始状态(有n个石子,没有被取过)g(x)=n;

View Code
// I'm lanjiangzhou//C#include <stdio.h>#include <stdlib.h>#include <string.h>#include <ctype.h>#include <math.h>#include <time.h>//C++#include <iostream>#include <algorithm>#include <cstdio>#include <cstdlib>#include <cmath>#include <cstring>#include <cctype>#include <stack>#include <string>#include <list>#include <queue>#include <map>#include <vector>#include <deque>#include <set>using namespace std;//*************************OUTPUT*************************#ifdef WIN32#define INT64 "%I64d"#define UINT64 "%I64u"#else#define INT64 "%lld"#define UINT64 "%llu"#endif//**************************CONSTANT***********************#define INF 0x3f3f3f3f// aply for the memory of the stack//#pragma comment (linker, "/STACK:1024000000,1024000000")//endconst int maxn =100+10;int a[maxn];int main(){    int n;    while(scanf("%d",&n)!=EOF){        int t=0;        int flag=0;        for(int i=0;i<n;i++){            scanf("%d",&a[i]);            t=(t^a[i]);            if(a[i]>1){                flag++;            }        }        if(t==0){            if(flag) printf("No\n");            else printf("Yes\n");        }        else if(t){            if(flag) printf("Yes\n");            else printf("No\n");        }    }    return 0;}