• ZOJ1913 Euclid's Game (第一道简单的博弈题)


    题目描述:

    Euclid's Game

    Time Limit: 2 Seconds      Memory Limit: 65536 KB

    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

    分析:

    若存在x=k*y+r(k>1)则谁先面对x=k*y+r(k>1),即x>2*y的局势谁赢,
    因为此时可以拿成 (x%y,y) 或 (x%y+y,y)这两种局势,而这两种局势中要达到最终(num,0)步数必然
    一奇一偶(相差一步),则此时只要选择自己取胜的最优策略就可以了
    当然若一开始x<2*y,则看到达(num,0)的步数的奇偶性来决定胜负

    而过程类似于欧几里得算法(估计也是这道题为何叫欧几里得的游戏的原因所在),递归就行了。

    伪代码:

    f(a,b)

    if a%b == 0 --->先手赢

    else  if  a<2*b ---> 递归

    else  if  a>2*b --->当前者赢

    end if

    代码:

    #include<cstdio>
    #include<algorithm>
    using namespace std;
    int ice(int a,int b){
        if(a < b)
         swap(a,b);
         if(a % b == 0)
              return 1;
         else if(a < 2*b)//a=b+r,k==1;记步数
              return !(ice(a-b,b));//先手赢返回1,否则返回0;
         return 1;//a>2*y,直接先手赢。
    
      }
    
    int main(){
         int a,b,c;
         while(scanf("%d%d",&a,&b) != EOF){
              if(a == 0 && b == 0)
                   break;
            c = ice(a,b);
            if(c)
              printf("Stan wins
    ");
            else
               printf("Ollie wins
    ");
    
         }
    return 0;
    }
    Keep It Simple and Stupid.
  • 相关阅读:
    回忆Partition算法及利用Partition进行快排
    2019春第七周作业
    2019春第六周作业
    2019春第五周作业
    2019年春季学期第四周作业。
    2019年春季学期第三周作业
    2019年春季学期第二周作业
    2019春第一周作业编程总结
    PTA编程总结2—币值转换
    第七周编程总结
  • 原文地址:https://www.cnblogs.com/FleetingTime/p/3733970.html
Copyright © 2020-2023  润新知