C - A Coloring Game
Crawling in process...Crawling failedTime Limit:500MS Memory Limit:65536KB 64bit IO Format:%I64d & %I64u
Description
Two players play a graph coloring game. They make moves in turn, first player moves first. Initially they take some undirected graph. At each move, a player can color an uncolored vertex with either white or black color (each player can use any color, possibly different at different turns). It's not allowed to color two adjacent vertices with the same color. A player that can't move loses.
After playing this game for some time, they decided to study it. For a start, they've decided to study very simple kind of graph — a chain. A chain consists of N vertices, v 1, v 2,..., v N, and N-1 edges, connecting v 1 with v 2, v 2 with v 3,..., v N-1 with v N.
Given a position in this game, and assuming both players play optimally, who will win?
Input
The first line of input contains the integer
N,
.
The second line of input describes the current position. It contains N digits without spaces. i th digit describes the color of vertex v i: 0 — uncolored, 1 — black, 2 — white. No two vertices of the same color are adjacent.
The second line of input describes the current position. It contains N digits without spaces. i th digit describes the color of vertex v i: 0 — uncolored, 1 — black, 2 — white. No two vertices of the same color are adjacent.
Output
On the only line of output, print "
FIRST
" (without quotes) if the player moving first in that position wins the game, and "
SECOND
" (without quotes) otherwise.
Sample Input
sample input | sample output |
5 00100 | SECOND |
sample input | sample output |
4 1020 | FIRST |
博弈 sg函数
赛后把这道题理解了一下。
首先,这道题目的sg函数通过总结可分为4类。
第一类:x00...00y(x==y) 形式的 这个状态的sg函数是0.
第二类:x00...00y(x!=y) 形式的 这个状态的sg函数是1.
第三类:x00...00 形式的 这个状态的sg函数是 零的个数。例如:1000 的sg函数是3。
第四类:0000...000 形式的 如果零的个数是偶数,则sg函数是0 ,否则sg函数不等于0,具体就不管了。
#include <cstdio>
#include <cstring>
using namespace std;
char str[100010];
int main() {
int n;
while (~scanf("%d", &n)) {
scanf("%s", str);
bool flag = true;
for (int i = 0; i < n; i++) if (str[i] != '0') {
flag = false;
break;
}
if (flag) {
if (n % 2 == 1) printf("FIRST\n");
else printf("SECOND\n");
continue;
}
int ans = 0;
int p = 0;
while (str[p] == '0') p++;
if (p) ans ^= p;
int q = n;
while (str[q - 1] == '0') q--;
if (q < n) ans ^= n - q;
int pre = p, cnt = 0;
for (int i = p + 1; i < q; i++)
if (str[i] == '0') {
cnt++;
} else {
if (cnt && str[i] == str[pre]) ans ^= 1;
pre = i;
cnt = 0;
}
if (ans) printf("FIRST\n");
else printf("SECOND\n");
}
return 0;
}