【博弈】HackerRank _ stone_division

来源:互联网 发布:aloha软件 编辑:程序博客网 时间:2024/05/21 16:23

Consider the following game:

  • There are two players, First and Second, sitting in front of a pile of  stones. First always plays first.
  • There is a set, , of  distinct integers defined as .
  • The players move in alternating turns. During each turn, a player chooses some  and splits one of the piles into exactly  smaller piles of equal size. If no  exists that will split one of the available piles into exactly  equal smaller piles, the player loses.
  • Both players always play optimally.

Given , and the contents of , find and print the winner of the game. If First wins, print First; otherwise, print Second.

Input Format

The first line contains two space-separated integers describing the respective values of  (the size of the initial pile) and  (the size of the set). 
The second line contains  distinct space-separated integers describing the respective values of .

Constraints

Output Format

Print First if the First player wins the game; otherwise, print Second.

Sample Input 0

15 35 2 3

Sample Output 0

Second

Explanation 0

The initial pile has  stones, and . During First's initial turn, they have two options:

  1. Split the initial pile into  equal piles, which forces them to lose after the following sequence of turns: 
    stone-division.png
  2. Split the initial pile into  equal piles, which forces them to lose after the following sequence of turns: 
    stone-division-2.png

Because First never has any possible move that puts them on the path to winning, we print Second as our answer.

/*啊我也不是很懂,看别人的代码补得题*/#include <bits/stdc++.h>using namespace std;typedef long long LL;LL a[15];int m;map<LL,int>mp;int check(LL n){    if(mp.count(n))        return mp[n];    int ans=0;    for(int i=0;i<m;i++){        if(n%a[i]==0){            if(a[i]%2==0)/*能分成偶数块,先手必胜*/                return mp[n]=1;            else ans|=!check(n/a[i]);/*在下一次先手必输的情况下,也就是对于这局来说后手必输的情况下,就是这局先手必胜的情况*/        }    }    return mp[n]=ans;}int main(){    LL n;    scanf("%lld%d",&n,&m);    for(int i=0;i<m;i++)        scanf("%lld",&a[i]);    printf(check(n)?"First\n":"Second\n");    return 0;}

原创粉丝点击