HackerRank

来源:互联网 发布:python股票大数据分析 编辑:程序博客网 时间:2024/04/29 03:43

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

这个题是SG函数,嗯,其实就是记忆化递归吧~

直接枚举所有情况。

首先就是如果能分成偶数堆,那么先手必赢。然后如果分成的是奇数堆,那么继续递归处理,在这个处理中只要找到一个先手必输的,那么之前就是先手必赢的状态。

#include <iostream>#include <cstdio>#include <map>using namespace std;map<long long,bool>sg;long long n;int m;long long num[10];bool check(long long n){    if(sg.count(n))return sg[n];    bool ans = 0;    for(int i = 0 ; i < m ; ++i)    {        if(n%num[i] == 0)        {            if(num[i] % 2 == 0)return sg[n] = 1;            else ans |= !check(n/num[i]);        }    }    return sg[n] = ans;}int main(){    scanf("%lld%d",&n,&m);    for(int i = 0 ; i < m ; ++i)scanf("%lld",&num[i]);    printf(check(n)?"First\n":"Second\n");    return 0;}