HD 1525 Euclid's Game

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1525



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

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
 

题意:

两个人,两堆石头,玩游戏。每次从石头数多的那堆中拿走石头数少的那堆石头的个数的倍数个,保证拿了过后不能为负数。谁恰好使其中一堆石头数为0,谁使其中某一堆石头为0,谁赢。两人都足够聪明。

思路:

借助欧几里得算法的博弈。

显然如果a>b 且a>2*b  先拿者必赢 因为他可以决定是自己还是对手遇到状态(a%b,b)如果状态(a%b,b)为必输状态,他就让对手面对(拿走a-a%b个)。如果为必赢状态,他就自己面对(拿走-a%b-b个).

如果b<a<=2*b 只能到达(a%b,b)的状态。


#include<iostream>
#include<cstdio>
#define ll __int64

using namespace std;

int gcd(ll a,ll b)
{
    if(a<b) //求出谁大
        swap(a,b);
    if(b==0) //终止 必输状态
        return 0;
    if(a>2*b) //必胜
        return 1;

    return gcd(b,a%b)^1; //和拿了之后的输赢情况相反
}

int main()
{
   ll a,b;

   while(scanf("%I64d%I64d",&a,&b)!=EOF && a+b)
   {
       int ans=gcd(a,b);
       if(ans)
            printf("Stan wins\n");
       else
            printf("Ollie wins\n");
   }
   return 0;
}
 




你可能感兴趣的:(HD 1525 Euclid's Game)