Little Sub and Johann (NIM遊戲與 SG函數)

  • 題目鏈接:http://acm.hznu.edu.cn/OJ/problem.php?id=2591

  • 題意:有 n 堆石子,兩個玩家輪流操作,每次操作只能去掉一堆石子或者在一堆有x個石子的石堆中移除y個石子,並且滿足 gcd(x, y) = 1。直到一個玩家無法操作,則另一個玩家勝利。問先手贏還是後手贏。

  • 顯然符合NIM遊戲,只要能算出sg函數值即可判斷。算出每個石堆的SG函數,然後求其異或和。如果結果爲零則後手贏,否則先手贏。
    打表尋找規律,可以發現當x爲質數時,sg[x]=x是第幾個質數+1。
    當x不爲質數時,sg[x]=sg[p]且p是x的最小質因子。sg[1] = 1

    寫一個類似線性篩的循環即可,線性篩保證每個數字都是被最小質因子篩到。

    //考察NIM遊戲,以及找規律?證明sg函數取值就留給自行思考。

#include<bits/stdc++.h>
#define pi acos(-1)
#define fastio ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
using namespace std;
typedef pair<int, int> PII;
typedef long long LL;
const int INF = 0x3f3f3f3f;
const LL LL_INF = 0x3f3f3f3f3f3f3f3f;
const int maxn = 2e6 + 10;
const LL mod = 1000000007;


int a[maxn];
int prime[maxn];
int sg[maxn], fac[maxn];

int is()
{
    memset(prime, 1, sizeof(prime));
    for(int i=2;i*i<maxn;i++){
        if(prime[i]){
            for(int j=i+i;j<maxn;j+=i){
                prime[j]=0;
                if(fac[j] == 0)fac[j] = i;
            }
        }
    }
}

void init()
{
    is();
    int tot = 1;
    sg[1] = 1;
    for(int i=2; i<maxn; i++){
        if(prime[i]) sg[i] = ++tot;
        else sg[i] = sg[fac[i]];
    }
}

int main()
{
    init();
    int T;
    scanf("%d", &T);
    while(T--){
        int n;
        scanf("%d", &n);
        for(int i=1; i<=n; i++){
            scanf("%d", &a[i]);
            //printf("%d ", a[i]);
        }//puts("");
        for(int i=1; i<=n; i++){
            a[i] = sg[a[i]];
        }
        int ans = a[1];
        for(int i=2; i<=n; i++){
            ans = ans ^ a[i];
        }
        if(ans == 0) {
            printf("Long live with King Johann!\n");
        }
        else printf("Subconscious is our king!\n");
    }
    return 0;
}

/*

2
4
1 10 5 7
4
9 2 3 6

*/

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