Euclid’s Game(POJ-2348)
题面
Two players, Stan and Ollie, play, starting with two natural numbers. Stan, the first player, subtracts any positive multiple of the lesser of the two numbers from the greater of the two numbers, provided that the resulting number must be nonnegative. Then Ollie, the second player, does the same with the two resulting numbers, then Stan, etc., alternately, until one player is able to subtract a multiple of the lesser number from the greater to reach 0, and thereby wins. For example, the players may start with (25,7):
1 25 7 2 11 7 3 4 7 4 4 3 5 1 3 6 1 0
an Stan wins.
输入
The input consists of a number of lines. Each line contains two positive integers giving the starting two numbers of the game. Stan always starts.
输出
For each line of input, output one line saying either Stan wins or Ollie wins assuming that both of them play perfectly. The last line of input contains two zeroes and should not be processed.
样例输入
134 12
215 24
30 0
样例输出
1Stan wins
2Ollie wins
提示
无
思路
当局面为(a, b) a<=b,b%a==0的时候,先手必胜;当b>2*a的时候,先手可以将必败态转化为必胜态,即若b=a*x+y,取走a*x会导致必败态(将必胜态留给对手,此时必败)的时候,由于x>2,先手可以选择取走a*(x-1)而将必败态留给对手;当2*a>b>a时,先手只能将局面取b-a,状态互换。
例如:
(0, 1) 先手必败
(1, 2) 先手必胜
当局面为(2, 3)时,先手只能取成(1, 2),将必胜态留给对手,此时先手必败
当局面为(2, 5)时,先手可以取成(1, 2)和(2, 3),毫无疑问,取成(2, 3)可以将必败态留给对手,此时先手必胜。
代码
1using namespace std;
2
3int main(){
4 int a, b;
5 while(~scanf("%d %d", &a, &b) && a && b)
6 {
7 int win = 1;
8 while(1){
9 if(a > b) swap(a, b);
10 if(b%a==0 || b-a>a) break;
11 b -= a;
12 win = !win;
13 }
14 if(win){
15 printf("Stan wins\n");
16 }else{
17 printf("Ollie wins\n");
18 }
19 }
20}