[2016ACM多校] HDU5724 博弈论 SG

来源:互联网 发布:淘宝里怎么打开链接 编辑:程序博客网 时间:2024/06/05 13:24

题意

n行棋盘,每行20个放有棋子,两人每次可以把一个棋子移动到它右边第一个空位,不能操作者失败,输出先手是否必胜。

思路

典型的Nim游戏,搜索求SG函数,然后把每行的SG(状态)值异或一下。用for把代码变得很短,感觉很良好。

AC代码 C

#include <stdio.h>#include <string.h>#define LEN 20int sg[1 << LEN];int dfs(int s){    if(sg[s] >= 0)        return sg[s];    int i, np;    bool vis[LEN << 1] = {false};   //标记当前点能到达哪些状态,要开在里面    for(i=0; i<LEN; i++)        if(s & 1 << i)        {            for(np=i+1; np<LEN && s&1<<np; np++);            if(np >= LEN)                break;            vis[dfs(s ^ 1 << i ^ 1 << np)] = true;        }    for(i=0; vis[i]; i++);  //sg(s)值是他所不能到达的最小自然数    return sg[s] = i; }int main(){    int t, n, m, p, s, ans;    memset(sg, -1, sizeof sg);    for(s=1, sg[0]=0; s<1<<LEN; s++)        dfs(s);    scanf("%d", &t);    while(t-- && scanf("%d", &n))    {        for(ans=0; n-- && scanf("%d", &m); ans^=sg[s])            for(s=0; m-- && scanf("%d", &p); s|=1<<p-1);        puts(ans ? "YES" : "NO");    }    return 0;}
0 0
原创粉丝点击