HDU 1525 Euclid's Game(博弈)

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):

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

题意:

有两个玩家,Stan 和 Ollie, 在玩游戏。初始有两个自然数。Stan是先手,每次把大的数字减去小的数字的任意倍数,但是不能使数字变成负数。然后Ollie进行同样的操作,直到有一个玩家使一个数字变为零。

题解:

有两个数a,b,假设a>b,那么如果一开始a%b==0那么肯定是先手赢,接下来考虑两个数互相减的情况:如果a>2b,那么先手肯定能赢,因为他可以a-=b。此时a仍然大于b,掌握着主动权,所以先手必赢。如果b<a<2b,就只能模拟步数判断谁赢了。

#include<iostream>
#include<algorithm>
using namespace std;
typedef long long LL;
int main()
{
    int a,b;
    while(cin>>a>>b,a||b)
    {
        if(a<b)
            swap(a,b);
        int ta=a,tb=b;
        int num=0;
        while(tb)
        {
            if(ta>2*tb||ta%tb==0)
                break;
            ta-=tb;
            num++;
            swap(ta,tb);
        }
        if(num%2==0)
            cout<<"Stan wins"<<endl;
        else
            cout<<"Ollie wins"<<endl;
    }
    return 0;
}
posted @ 2017-11-30 19:14  Zireael  阅读(233)  评论(0编辑  收藏  举报