hdu 5724 SG函数+状压 详解

Chess

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 3506    Accepted Submission(s): 1448


 

Problem Description

Alice and Bob are playing a special chess game on an n × 20 chessboard. There are several chesses on the chessboard. They can move one chess in one turn. If there are no other chesses on the right adjacent block of the moved chess, move the chess to its right adjacent block. Otherwise, skip over these chesses and move to the right adjacent block of them. Two chesses can’t be placed at one block and no chess can be placed out of the chessboard. When someone can’t move any chess during his/her turn, he/she will lose the game. Alice always take the first turn. Both Alice and Bob will play the game with the best strategy. Alice wants to know if she can win the game.

 

Input

Multiple test cases.

The first line contains an integer T(T≤100), indicates the number of test cases.

For each test case, the first line contains a single integer n(n≤1000), the number of lines of chessboard.

Then n lines, the first integer of ith line is m(m≤20), indicates the number of chesses on the ith line of the chessboard. Then m integers pj(1≤pj≤20) followed, the position of each chess.

 

Output

For each test case, output one line of “YES” if Alice can win the game, “NO” otherwise.

 

Sample Input

 

2 1 2 19 20 2 1 19 1 18

 

Sample Output

 

NO YES

 

Author

HIT

 

Source

2016 Multi-University Training Contest 1

题意:

一个棋盘有n行,每行20格子,每行都有一些棋子,两个人轮流进行这个操作:选择某一行一个棋子移动到该行右边最近的一个空的格子。不能移动的人输。问先手是否能赢。

分析:
SG函数的应用,终结点是这一行没有棋子可以走,即0,然后逆推出其他结点的SG函数。每一行的状态看成是一个结点,然后把状态二进制压缩,1表示有棋子,0表示空格。

(貌似数据在  n<=20 以内都可以用状态压缩来进行)

#include<cstdio>
#include<cstring>
using namespace std;
int sg[1<<21],vis[21];//PN点 记录可达状态
int getSG(int x)//在该状态下
{
  memset(vis,0,sizeof(vis));//每次初始化状态
  for(int i=20; i>=0; i--)//逆推
  {
    if(x&(1<<i))//在该状态下  i空格没有棋子
    {
      int t=x;
      for(int j=i-1; j>=0; j--)//寻找i前面的最近空格
        if(!(x&(1<<j)))//j空格有棋子
        {
          t^=(1<<i)^(1<<j);//在t状态下 棋子从j空格移动到i空格 离他最近的空格子
          vis[sg[t]]=1;//该棋子走向空格
          break;
        }
    }
  }
  for(int i=0; i<=20; i++)if(!vis[i])return i;//返回PN值
}
int main()
{
  memset(sg,0,sizeof(sg));//初始化
  for(int i=0; i<(1<<20); i++)//每一个状态的SG
    sg[i]=getSG(i);
  int T;
  scanf("%d",&T);
  while(T--)
  {
    int n,m,x,ans=0;
    scanf("%d",&n);
    for(int i=0; i<n; i++)
    {
      scanf("%d",&m);
      int st=0;
      while(m--)
      {
        scanf("%d",&x);
        st|=1<<(20-x); //是从右边开始的,21这个位置为0
      }
      ans^=sg[st];
    }
    printf("%s\n",ans?"YES":"NO");
  }
  return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41668093/article/details/82952611