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
题目链接
参考题解

给两个数,两人依次取,规则是:每次从大的数那取(两数目相等时任选其一),取的数目只能为小的数的正整数倍。最后取完其中一个数的胜。问给定情况下先手胜负情况。
经典博弈问题,看谁先把其中一个数字变成0。
分析一下两个状态:
1、x == y:这样的状态一定是先手赢,因为一次可以直接取完。
2、假设x > y(如果不是的话可以swap函数换一下):那么x一定可以这样表示:x = y * k + r;
(1)k <= 1:这个时候是(r + y, y)的状态,那么下一步一定是(r, y),其中一定有一种情况是赢的。直接模拟一下就可以了。
(2)k >= 2:这中情况下,进行操作的人是占有主动权的,即想赢就赢,想输则输。因为k >= 2,那么下一步可以变为(r + y, y), 也可以是(r, y),这要看是否对自己有利,其中有一种是一定能赢的,所以这个人是一定可以赢的。
下面直接上代码:

#include <cstdio>
#include <cstring>
#include <algorithm>
#define ll long long
using namespace std;

int main()
{
    int n, m;
    while(scanf("%d%d", &n, &m), n + m)
    {
        int flag = 1;
        if(n == m)
        {
            printf("Stan wins\n");
            continue ;
        }
        while(n && m)
        {
            if(n < m)   swap(n, m);//让大的在前
            if(n / m > 1)   break ;	//如果n大于m的两倍当前操纵者一定能赢
            n %= m;
            if(!(n && m))   break ;//如果其中一个数字等于0,结束模拟
            flag ^= 1;//换一下操纵者
        }
        if(flag)    printf("Stan wins\n");
        else    printf("Ollie wins\n");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_40788897/article/details/82766652