POJ-2960(S-Nim)——博弈論,SG函數

題意:兩個人玩遊戲,規則是有n堆石子,分別有a1,a2,...,an顆石頭,每次從一堆石子中取一些石子,但是可取的石子數是規定了的,必須是{s1,s2,...,sk}中的一個,誰無法操作就輸。

思路:一開始我還是不懂的,不知道怎麼選擇SG函數值。但是回去研讀了一下SG函數的定義,就明白了:相對於樸素的NIM遊戲,可取的石子數是有限制的,那就按照SG函數的定義進行遞歸求解SG值,然後將每一堆的SG值異或,判定一下就可以知道贏還是輸。

代碼:
#include <map>
#include <set>
#include <cmath>
#include <stack>
#include <queue>
#include <vector>
#include <string>
#include <cstdio>
#include <cctype>
#include <cstring>
#include <sstream>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
#define maxn 100+5
#define clr(x,y) memset(x,y,sizeof(x))
int s[maxn],k;
int sg[10000+5];
int SG(int n)
{
    if(sg[n]>=0)return sg[n];
    if(!n) return sg[n]=0;
    int sk[100+5];
    clr(sk,0);
    for(int i=0;i<k&&s[i]<=n;i++)
        sk[SG(n-s[i])]=1;
    int ant=-1;
    for(int i=0;ant==-1;i++)
        if(!sk[i])
            ant=i;
    return sg[n]=ant;
}
int main()
{
    int m,n;
    while(scanf("%d",&k),k)
    {
        for(int i=0;i<k;i++)
            scanf("%d",&s[i]);
        sort(s,s+k);
        scanf("%d",&m);
        clr(sg,-1);
        while(m--)
        {
            int ans=0,a;
            scanf("%d",&n);
            for(int i=0;i<n;i++)
            {
                scanf("%d",&a);
                ans^=SG(a);
            }
            if(!ans)printf("L");
            else printf("W");
        }
        printf("\n");
    }
    return 0;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章