链接:https://ac.nowcoder.com/acm/contest/1071/G
来源:牛客网
时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 32768K,其他语言65536K
64bit IO Format: %lld
题目描述
Bessie is playing a number game against Farmer John, and she wants you to help her achieve victory.
Game i starts with an integer Ni (1 <= Ni <= 1,000,000). Bessie goes first, and then the two players alternate turns. On each turn, a player can subtract either the largest digit or the smallest non-zero digit from the current number to obtain a new number. For example, from 3014 we may subtract either 1 or 4 to obtain either 3013 or 3010, respectively. The game continues until the number becomes 0, at which point the last player to have taken a turn is the winner.
Bessie and FJ play G (1 <= G <= 100) games. Determine, for each game, whether Bessie or FJ will win, assuming that both play perfectly (that is, on each turn, if the current player has a move that will guarantee his or her win, he or she will take it).
Consider a sample game where Ni = 13. Bessie goes first and takes 3, leaving 10. FJ is forced to take 1, leaving 9. Bessie takes the remainder and wins the game.
输入描述:
- Line 1: A single integer: G
- Lines 2…G+1: Line i+1 contains the single integer: Ni
输出描述:
- Lines 1…G: Line i contains ‘YES’ if Bessie can win game i, and ‘NO’ otherwise.
示例1
输入
复制
2
9
10
输出
复制
YES
NO
说明
For the first game, Bessie simply takes the number 9 and wins. For the second game, Bessie must take 1 (since she cannot take 0), and then FJ can win by taking 9.
思路
博弈论
本题最后取完者胜,
所以终态n=0为先取者的必败点,
可以用sg函数来求解。
sg函数说明:
首先定义mex(minimal excludant)运算,这是施加于一个集合的运算,表示最小的不属于这个集合的非负整数。例如mex{0,1,2,4}=3、mex{2,3,5}=0、mex{}=0。
对于任意状态 x , 定义 SG(x) = mex(S),其中 S 是 x 后继状态的SG函数值的集合。如 x 有三个后继状态分别为 SG(a),SG(b),SG( c),那么SG(x) = mex{SG(a),SG(b),SG( c)}。 这样 集合S 的终态必然是空集,所以SG函数的终态为 SG(x) = 0,当且仅当 x 为必败点P时。
---------------from sg函数详解传送门
#include <iostream>
#include <string.h>
using namespace std;
const int N = 1e6;
int f[5],sg[N+2];
int getSg(int n)
{
if(sg[n]!= -1)
{
return sg[n];
}
int minx = 10,maxx = -1;
int x = n;
while(x)
{
int t = x%10;
if(t)
{
minx = min(minx,t);
maxx = max(maxx,t);
}
x /= 10;
}
f[0] = getSg(n-minx);
f[1] = getSg(n-maxx);
for(int i = 0; ; i++)
{
if(i==f[0]||i==f[1])
continue;
else
{
sg[n] = i;
break;
}
}
return sg[n];
}
int main()
{
memset(sg,-1,sizeof(sg));
sg[0] = 0;
for(int i = 1; i <= N; i++)
{
getSg(i);
}
int n;
cin>>n;
while(n--)
{
int x;
cin>>x;
cout<<(sg[x]?"YES":"NO")<<endl;
}
return 0;
}