POJ 2348 - Euclid's Game (Game Theory)
Description
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):
an Stan wins.
25 7 11 7 4 7 4 3 1 3 1 0
an Stan wins.
Input
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.
Output
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.
Sample Input
34 12 15 24 0 0
Sample Output
Stan wins Ollie wins
.题意是给你两个整数a和b,Sten和Ollie轮流去两者数中大数减去小数的整倍数,结果不能小于零,Sten先手,在自己的回合得到0者获胜,问谁获胜。
思路:a和b之间的大小关系分以下三种。(假设a < b)
一:b是a的整倍数,必胜。
二:b - a < a
这种情况下只能用b减去a,没有选择,必胜态和必败态互相转换。
三:b - a > a
这里我们假设b - ax < a;我们来讨论一下减去a * (x - 1)的情况,如果减去以后是必败态,那么当前为必胜态。
如果减去之后为必胜态,我们知道b - ax的状态是b - a(x - 1)唯一可以转移到的状态,因此b - ax为必败态,当前为必胜态。
所以b - a > a为必胜。
- int main()
- {
- int a , b;
- while(~scanf("%d%d" , &a , &b) , a||b)
- {
- int ok = 1;
- while(1)
- {
- if(a > b)swap(a , b);
- if(b % a == 0)break;
- if(b - a > a)break;
- b -= a;
- ok ^= 1;
- }
- if(ok)puts("Stan wins");
- else puts("Ollie wins");
- }
- return 0;
- }