版权声明:转载请注明出处 https://blog.csdn.net/xuyangxinlei/article/details/79710020
取球博弈
两个人玩取球的游戏。
一共有N个球,每人轮流取球,每次可取集合{n1,n2,n3}中的任何一个数目。
如果无法继续取球,则游戏结束。
此时,持有奇数个球的一方获胜。
如果两人都是奇数,则为平局。
假设双方都采用最聪明的取法,
第一个取球的人一定能赢吗?
试编程解决这个问题。
输入格式:
第一行3个正整数n1 n2 n3,空格分开,表示每次可取的数目 (0<n1,n2,n3<100)
第二行5个正整数x1 x2 ... x5,空格分开,表示5局的初始球数(0<xi<1000)
输出格式:
一行5个字符,空格分开。分别表示每局先取球的人能否获胜。
能获胜则输出+,
次之,如有办法逼平对手,输出0,
无论如何都会输,则输出-
例如,输入:
1 2 3
1 2 3 4 5
程序应该输出:
- 0 + 0 -
再例如,输入:
1 4 5
10 11 12 13 15
程序应该输出:
0 - 0 + +
再例如,输入:
2 3 5
7 8 9 10 11
程序应该输出:
- 0 0 0 0
- 资源约定:
import java.util.Arrays;
import java.util.Scanner;
public class Main {
static int[] n = new int[3];
static int[] x = new int[5];
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
n[0] = scan.nextInt();
n[1] = scan.nextInt();
n[2] = scan.nextInt();
for(int i=0;i<5;i++){
x[i] = scan.nextInt();
}
Arrays.sort(n);
for(int i=0;i<5;i++){
System.out.println(check(x[i],0,0)+" ");
}
}
public static int check(int x,int y1,int y2){//x为剩余球,y1为自己取球个数,y2为对方取球个数
if(x<n[0]){
if(y1%2==1&&y2%2==0){
return 1;
}
else if(y1%2==y2%2){
return 0;
}
else{
return -1;
}
}
int flag = 0;//用于判断是否能平局
for(int i=0;i<3;i++){
if(x<n[i]) break;
int check = -check(x-n[i],y2,y1+n[i]);
if(check==1){
return 1;
}
else if(check==0){
flag = 1;
}
}
if(flag==1){
return 0;
}
return -1;
}
}
利用递归,理清楚“最聪明”的逻辑