小a和小B两个人玩抢糖果的游戏,小a先生每个人轮流操作,可以从糖果堆里拿走,任意非零平方数个糖果,如果糖果堆里没有糖果了,则无法操作的玩家输掉游戏给你正整数N表示糖果的总数已知,两个人都采取最优策略,如果小a会赢得比赛,则返回true,否则返回false。
参考代码
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int res = dfs(n, 0) ? 1 : 0;
if(res==1) System.out.println("赢的是小哈");
else System.out.println("赢的是小罗");
}
public static boolean dfs(int n, int cnt) {
if (n == 0) {
return cnt % 2 == 1;
}
//cnt是拿的次数,空的时候拿了偶数次,就是A赢了
if (n == 1) {
return cnt % 2 == 0;
}
// temp是每次要拿的糖果
int temp = 1;
//最少拿一个
int i=1;
while (temp <= n) {
i++;
temp =i*i;
}
i--;
temp=i*i;
while((n-temp)%2!=0 && temp>1) {
i--;
temp =i*i;
}
System.out.println(temp);
return dfs(n - temp, cnt + 1);
}