题解:CF603C Lieges of Legendre

· · 题解

首先写出 SG 函数的转移式:SG(x) = \oplus_{i=1}^k SG(\frac{x}{2}) \oplus SG(x-1),当 x 不是偶数时没有 \oplus_{i=1}^k SG(\frac{x}{2}) 这一项。由于是异或,所以 k 先对 2 取模。

然后打表发现如下事实:

于是当满足上面的条件时直接返回,那么对于每个数暴力求解 SG 函数实际上只会递归 O(\log V) 次,因为每次递归 SG(\frac{x}{2}) 时大小折半,而递归 SG(x-1) 时可以直接得到答案。

由于我用了 map 存了下值,所以时间复杂度是 O(n \log^2 V) 的。

#include<bits/stdc++.h>
using namespace std;
//#define int long long
//#define lowbit(x) (x&(-x))
//#define bp push_back
//#define sz size
//#define cl clear
const int maxn = 1e5+114;
map<int,int> sg,vis;
int n,k;
int solve(int u){
    if(vis[u]==1) return sg[u];
    vis[u]=1;   
    if(k%2==0) return sg[u]=(u<=2?u:((u%2)^1));
    if(k%2==1&&u>=10&&u%2==1) return (sg[u]=0); 
    if(u==0){
        return (sg[u]=0);
    }
    int cnt[4]={0,0,0,0};
    int res=solve(u/2);
    int ans=0;
    for(int i=1;i<=(k%2);i++) ans^=res;
    if(u%2==0) cnt[ans]++;
    cnt[solve(u-1)]++;
    while(cnt[sg[u]]!=0) sg[u]++;
    return sg[u];
}
//k%2==0
//sg(i)=[i<=2?i:i%2^1]
//k%2==1
//比较小直接暴力 
int main(){
    ios::sync_with_stdio(0);
    cin.tie(0),cout.tie(0);
    cin>>n>>k;
    int Nim=0;
    for(int i=1;i<=n;i++){
        int x;
        cin>>x;
        Nim^=solve(x); 
    }
    cout<<(Nim!=0?"Kevin\n":"Nicky\n");
    return 0;
}