HackerRank - stone-division

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 3
5 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;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值