博弈論專題——推理與動態規劃相關博弈之POJ2348

say_c_box發表於2016-08-12

Euclid's Game
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 8827   Accepted: 3605

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


給兩個整數a和b,兩個人先後用較大的數減去較小數的整數倍,並且保證相減後為非負數。先把一個數變為0的人獲勝。

很顯然,當大數是小數的整數倍時為必勝態。

從這道題學會一個叫做自由度的東西,感覺能夠為博弈推理提供思路。

博弈基本就是一個推理必勝態和必敗態的過程。自由度越低越好推理。

不妨假設b為兩個數中的較大數。

如果b-a<a

那麼只能選擇用b去減a,如果後繼態是必勝態,那麼該狀態是必敗態,否則就是必勝態。

如果b-a>a呢?

我們怎麼能夠轉移到自由度較低的情況。

假設x是是的b-x*a<a的整數。

那麼我們用b減去(x-1)*a。這個就變成了第一種情況,如果第一種情況是必敗態,那麼此時就是必勝態。

如果減去(x-1)*a是必勝態呢?那麼b-a*x是不是就變成了必敗態?(有點繞,仔細想想),所以當前狀態還是必勝態。

所以就是比誰先達到自由度高的情況即可。

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
using namespace std;


int a,b;
void solve(){
    bool f=true;
    for(;;){
        if(a>b)
            swap(a,b);
        if(b%a==0)
            break;
        if(b-a>a)
            break;
        b-=a;
        f=!f;
    }
    if(f)
        puts("Stan wins");
    else
        puts("Ollie wins");
}

int main(){
    while(scanf("%d%d",&a,&b)){
        if(a==0&&b==0)
            break;
        solve();
    }
}













相關文章