Cutting Game
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 3200 | Accepted: 1179 |
Description
Urej loves to play various types of dull games. He usually asks other people to play with him. He says that playing those games can show his extraordinary wit. Recently Urej takes a great interest in a new game, and Erif Nezorf becomes the victim. To get away from suffering playing such a dull game, Erif Nezorf requests your help. The game uses a rectangular paper that consists of W*H grids. Two players cut the paper into two pieces of rectangular sections in turn. In each turn the player can cut either horizontally or vertically, keeping every grids unbroken. After N turns the paper will be broken into N+1 pieces, and in the later turn the players can choose any piece to cut. If one player cuts out a piece of paper with a single grid, he wins the game. If these two people are both quite clear, you should write a problem to tell whether the one who cut first can win or not.
Input
The input contains multiple test cases. Each test case contains only two integers W and H (2 <= W, H <= 200) in one line, which are the width and height of the original paper.
Output
For each test case, only one line should be printed. If the one who cut first can win the game, print "WIN", otherwise, print "LOSE".
Sample Input
2 2 3 2 4 2
Sample Output
LOSE LOSE WIN
Source
POJ Monthly,CHEN Shixi(xreborner)
题目大意:两个选手把宽为w长为h的矩形按照纵或横随意切,最先切出1*1的选手win,问先手是win还是lose。
如果先手拿到最终状态(1*1)的矩阵一定是lose,所以可以设sg[1][1]=0。然后根据组合游戏里面的sg函数和sg定理把sg的数组补全就求得解了。还有一个问题就是关于(w,h)的后续状态怎么表示,因为选手可以从(w,h)分裂的两个矩阵中随意挑选出一个来切,不能确定他会切哪一个。解决方法是用sg[a][b]^sg[c][d]表示((
a,b)和(c,d)由(w,h)分裂而成)。
#include<stdio.h>
#include<string.h>
int sg[202][202];
int dfs(int w,int h)
{
int vis[205];
if(sg[w][h]!=-1) return sg[w][h];
memset(vis,0,sizeof(vis));
int i;
for(i=2;i+i<=w;i++) vis[dfs(i,h)^dfs(w-i,h)]=1;
for(i=2;i+i<=h;i++) vis[dfs(w,i)^dfs(w,h-i)]=1;
for(i=0;vis[i];i++);
return sg[w][h]=sg[h][w]=i;
}
int main()
{
int w,h;
memset(sg,-1,sizeof(sg));
sg[1][1]=0;
while(scanf("%d %d",&w,&h)!=EOF)
{
if(dfs(w,h)==0) puts("LOSE");
else puts("WIN");
}
return 0;
}