hdu1525(简单博弈)

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

首先,规定a始终大于b,若a>b&&a<2*b,则只有一种操作a-b,
若a>=2b,则先手总能做到使得b>=1/2a&&a>b,则后手只能有一种操作c=a-b<a-1/2a=1/2a,即操作后a>=2c,又恢复到先手状态了,
先手只需要一直这样循环到出现c=1,或者a%c==0,胜利即可,即先手必胜。

#include<iostream>
#include<cstring>
#include<string>

using namespace std;
const char s[][20]={"Stan wins", "Ollie wins"};
int main()
{
	
	ios::sync_with_stdio(false); cin.tie(0);
	int a,b;
	while(cin>>a>>b)
	{
		if(a==0&&b==0)
		break;
		if(a<b)swap(a,b);
		if(a%b==0)cout<<s[0]<<endl;
		else{
			int t=0;
			while(a>b&&a<b*2)
			{
				a-=b;
				t=(t+1)%2;
				if(a<b)
				swap(a,b);
			}
			if(a>=b*2)
			{
				cout<<s[t]<<endl;
			}
			else cout<<s[t^1]<<endl;//实际上就是a==0&&b==0,上一个胜利了
		}
 }
}在这里插入代码片
发布了109 篇原创文章 · 获赞 35 · 访问量 6021

猜你喜欢

转载自blog.csdn.net/weixin_43965698/article/details/90454230