LightOJ 1296 Again Stone Game(SG函数)

Alice and Bob are playing a stone game. Initially there are n piles of stones and each pile contains some stone. Alice stars the game and they alternate moves. In each move, a player has to select any pile and should remove at least one and no more than half stones from that pile. So, for example if a pile contains 10 stones, then a player can take at least 1 and at most 5 stones from that pile. If a pile contains 7 stones; at most 3 stones from that pile can be removed.

Both Alice and Bob play perfectly. The player who cannot make a valid move loses. Now you are given the information of the piles and the number of stones in all the piles, you have to find the player who will win if both play optimally.

Input
Input starts with an integer T (≤ 100), denoting the number of test cases.

Each case starts with a line containing an integer n (1 ≤ n ≤ 1000). The next line contains n space separated integers ranging in [1, 109]. The ith integer in this line denotes the number of stones in the ith pile.

Output
For each case, print the case number and the name of the player who will win the game.

Sample Input
5
1
1
3
10 11 12
5
1 2 3 4 5
2
4 9
3
1 3 9
Sample Output
Case 1: Bob
Case 2: Alice
Case 3: Alice
Case 4: Bob
Case 5: Alice

题意

有n堆石子,Alice先手,双方轮流,每次可以取不超过一半的石子走,谁不能取了谁输

思路

数据范围很大,直接打表肯定不行,那肯定有规律,那么我们先打几个SG值找一下规律

int sg[35],vis[35];
void getSG()
{
    int i,j;
    memset(sg,0,sizeof(sg));
    for(i=1; i<=30; i++)
    {
        memset(vis,0,sizeof(vis));
        for(j=1; j<=i/2;j++)//j为每次可以取走的石子数
            vis[sg[i-j]]=1;//sg[i-j]表示后继状态
        for(j=0; j<=30; j++)
        {
            if(vis[j]==0)
            {
                sg[i]=j;
                break;
            }
        }
    }
}

sg[1]=0
sg[2]=1
sg[3]=0
sg[4]=2
sg[5]=1
sg[6]=3
sg[7]=0
sg[8]=4
sg[9]=2
sg[10]=5
sg[11]=1
sg[12]=6
sg[13]=3
sg[14]=7
sg[15]=0
sg[16]=8
sg[17]=4
sg[18]=9
sg[19]=2
sg[20]=10
sg[21]=5
sg[22]=11
sg[23]=1
sg[24]=12
sg[25]=6
sg[26]=13
sg[27]=3
sg[28]=14
sg[29]=7
sg[30]=15
我们发现偶数i的SG值为这个数除以2即SG[i]=i/2,奇数i的SG值为他除以2的数的SG值,即SG[i/2],所以我们可以写出SG的递归函数

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
#include <math.h>
using namespace std;
int sg(int n)
{
    if(n%2==0)
        return n/2;
    else
        sg(n/2);
}
int main()
{
    int t,cas=1;
    scanf("%d",&t);
    while(t--)
    {
        int n;
        scanf("%d",&n);
        int ans=0;
        for(int i=0;i<n;i++)
        {
            int x;
            scanf("%d",&x);
            ans^=sg(x);
        }
        printf("Case %d: ",cas++);
        if(ans==0)
            printf("Bob\n");
        else
            printf("Alice\n");
    }
    return 0;
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值