LightOJ 1315【Nim博弈】 二維SG函式與記憶化搜尋
A Hyper Knight is like a chess knight except it has some special moves that a regular knight cannot do. Alice and Bob are playing this game (you may wonder why they always play these games!). As always, they both alternate turns, play optimally and Alice starts first. For this game, there are 6 valid moves for a hyper knight, and they are shown in the following figure (circle shows the knight).
They are playing the game in an infinite chessboard where the upper left cell is (0, 0), the cell right to (0, 0) is (0, 1). There are some hyper knights in the board initially and in each turn a player selects a knight and gives a valid knight move as given. And the player who cannot make a valid move loses. Multiple knights can go to the same cell, but exactly one knight should be moved in each turn.
Now you are given the initial knight positions in the board, you have to find the winner of the game.
Input
Input starts with an integer T (≤ 200), denoting the number of test cases.
Each case starts with a line containing an integer n (1 ≤ n ≤ 1000) where n denotes the number of hyper knights. Each of the next n
Output
For each case, print the case number and the name of the winning player.
Sample Input
2
1
1 0
2
2 5
3 5
Sample Output
Case 1: Bob
Case 2: Alice
題意:
給定一個棋盤,左上角為(0,0),棋盤中有多個騎士,每一個騎士只能按照圖中的6種方式移動,兩個人輪流移動棋盤中任意一個騎士,當輪到某一個人移動騎士時,棋盤中的騎士都已經不能移動了則判定為輸,Alice先移動棋盤中的騎士,最後輸出Alice和Bob誰贏誰輸。
題解:
典型的博弈SG函式,對每一個騎士的起始位置求SG值,然後將所有的SG值進行異或,如果其值為0,則先手必敗,即Bob 獲勝,否則先手必勝,Alice獲勝。又由於這道題是二維的,因此每一個位置都是由x和y兩個值來決定的,因此這道題無法使用打表的方式進行求SG值,需要時dfs的方式,SG初始化為-1即可。
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1100;
int sg[maxn][maxn];
int t, n;
int s[6][2] = {{1, -2}, {-1, -3}, {-1, -2}, {-2, -1}, {-3, -1}, {-2, 1}};
struct node {
int x, y;
}p[maxn];
int SG_dfs(int x, int y)
{
int i;
if(sg[x][y]!=-1)
return sg[x][y];
bool vis[maxn];
memset(vis,0,sizeof(vis));
int cnt = 0;
for(i=0;i<6;i++)
{
int tx = x+s[i][0];
int ty = y+s[i][1];
if(tx>=0 && ty>=0)
{
vis[SG_dfs(tx, ty)]=1;
}
}
int e;
for(i=0;;i++)
if(!vis[i])
{
e=i;
break;
}
return sg[x][y]=e;
}
int main(){
memset(sg, -1, sizeof(sg));
int Case = 1;
scanf("%d", &t);
while(t--){
scanf("%d", &n);
for(int i=0; i<n; i++){
scanf("%d%d", &p[i].x, &p[i].y);
}
for(int i=0; i<=n; i++){
SG_dfs(p[i].x, p[i].y);
}
int ans = 0;
for(int i=0; i<n; i++){
ans ^= sg[p[i].x][p[i].y];
}
printf("Case %d: ", Case++);
if(ans == 0) cout<<"Bob"<<endl;
else cout<<"Alice"<<endl;
}
}