POJ2348 Euclid's Game

原题链接:http://poj.org/problem?id=2348

Euclid’s Game

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

题解

我们可以把这个过程理解为一个多阶段 N i m ,有多堆石子,每堆石子都有一个可以取的次数,每次至少取一次,可以取多次,在取完上一堆后才能取下一堆,以样例中的第一组数据为例:

(34,12)可以取两个12,取完以后变成(12,10)
(12,10)只能取一次,变成(10,2)
(10,2)取5次取完变成(2,0)

那么转化为多阶段 N i m 游戏是3堆石子:2,1,5

在多阶段 N i m 中,如果先手取下一堆能够赢,那么在取这一对的时候就可以将这堆石子取的刚好剩下一个,强迫对手取完这一堆;反之,就可以直接将这堆石子取完,让对手去取下一堆。只有当某堆石子只能取一次的时候,先手的人别无选择必须取完。

那么问题就变得简单起来,只要谁掌握了先手(即第一个遇到可取次数大于1的情况),谁就能获胜。

代码
#include<cstdio>
#include<algorithm>
using namespace std;
int n,m;
bool check(int x,int y,bool p)
{
    if(x%y==0)return p;
    if(x/y>1)return p;
    return check(y,x%y,!p);
}
void ac()
{
    if(n<m)swap(n,m);
    if(check(n,m,1))printf("Stan wins\n");
    else printf("Ollie wins\n");
}
int main()
{
    while(scanf("%d%d",&n,&m)&&n&&m)ac();
    return 0;
}

猜你喜欢

转载自blog.csdn.net/ShadyPi/article/details/79940119