1. 程式人生 > >[博弈]Euclid's Game

[博弈]Euclid's Game

F12 sed enter contains tle lan 兩種 view perfect

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.

Examples

Input

34 12
15 24
0 0

Output

Stan wins
Ollie wins

正確解法:

輾轉相除法:

給定兩個整數 a和b ,兩個人輪流從較大的數字中減去較小的數字的整數倍。若其中一個數字變為0,則這個人就贏了。

首先保證 a<b 因為這兩個人決策跟 a,b 的位置沒有任何關系,有關系的只是他們的大小。

這樣就分為兩個情況:

1.  b-a<a

2.  b-a>a

若是第一種情況,那就不用寫了,直接模擬看最後是誰贏了。

若是第二種情況:兩個人都非常聰明,分為兩種情況:

把 b 直接減到 比a還小的狀況,那就變成了 1.的情況,之後的結果可能是贏,也可能是輸。

把 b 減到 b>a 的情況,那麽下一人必須作出 b=b-a 的決策。從而變成 1.的情況。

要不就直接到達情況,要不就多一步到達情況。

那麽我們就可以確定這個人剛開始必勝。

1  if(b%a==0)  break;
2             if(b-a>a)   break;
技術分享圖片
 1 #include<iostream>
 2 #include<cstdio>
 3 #include<string>
 4 #include<cstring>
 5 #include<map>
 6 #include<set>
 7 #include<vector>
 8 #include<queue>
 9 #include<algorithm>
10 #include<cmath>
11 using namespace std;
12 typedef long long ll;
13 const int inf=0x7fffffff;
14 const int N=1000000+100;
15 const int M=9999999;
16 const ll mod=1000000000+7;
17 
18 int main()
19 {
20     ll a,b;
21     while(scanf("%lld %lld",&a,&b)&&a&&b)
22     {
23         int f=1;
24         while(true)
25         {
26             if(a>b) swap(a,b);
27             if(b%a==0)  break;
28             if(b-a>a)   break;
29             b=b%a;
30             f=!f;
31         }
32         if(f)   cout<<"Stan wins"<<endl;
33         else cout<<"Ollie wins"<<endl;
34 
35     }
36 
37 
38     return 0;
39 }
View Code

[博弈]Euclid's Game