シンプルな問題設定ながら割と複雑。
https://yukicoder.me/problems/no/2800
問題
根付き木を使った2人ターン制ゲームを考える。
初期状態で各点は白く塗られている。
各自のターンでは白頂点を1つ選択すると、そこから根頂点までのパス上の点が黒く塗られる。
自分の手番で白点が存在しないと、負けになる。
根付き木が与えられるので、両者最適手を取ったときの勝者を答えよ。
また、先手が勝者なら、先手が勝てる初手を列挙せよ。
解法
点vのgrundy数を考える。
vの部分木で1回操作することで遷移可能なgrundy数をS(v)とすると、子頂点が2個c,dとあるとき、
S(v)は以下の和集合となる。
- S(c)の各値にg(d)のxorを取ったもの
- S(d)の各値にg(c)のxorを取ったもの
- g(c)とg(d)のxor
なお、g(v)はS(v)のmex値となる。
複数子頂点があるとき、トライ木にマージテクを適用することで、上記和集合を高速にとることができる。
struct BinarySumTrie { set<ll> V; ll x; struct node { ll v; node *nex[2]; node() { nex[0]=nex[1]=NULL;v=0; }; void add(ll s,int pos=20) { v++; if(pos>=0) { int c=(s>>pos)&1; if(!nex[c]) { nex[c]=new node(); } nex[c]->add(s,pos-1); } } ll gr(int pos,ll x) { // sum [0,s-1] ll num=1LL<<(pos); if(x&(1LL<<pos)) { if(!nex[1]) return 0; if(nex[1]->v<num) { return nex[1]->gr(pos-1,x); } else { if(!nex[0]) return num; return (num)^nex[0]->gr(pos-1,x); } } else { if(!nex[0]) return 0; if(nex[0]->v<num) { return nex[0]->gr(pos-1,x); } else { if(!nex[1]) return num; return (num)^nex[1]->gr(pos-1,x); } } return 0; } }; node root; BinarySumTrie() { x=0; } void add(ll s) { s^=x; if(V.count(s)) return; V.insert(s); root.add(s); } ll gr() { return root.gr(20,x); } }; int N; vector<int> E[202020]; BinarySumTrie bs[202020]; int G[202020]; vector<int> V; void dfs(int cur,int pre) { ll x=0; bs[cur].add(0); FORR(e,E[cur]) if(e!=pre) { dfs(e,cur); bs[e].x^=x; x^=G[e]; bs[cur].x^=G[e]; if(bs[cur].V.size()<bs[e].V.size()) { swap(bs[cur],bs[e]); } FORR(v,bs[e].V) bs[cur].add(v^bs[e].x); } G[cur]=bs[cur].gr(); } void dfs2(int cur,int pre,int g) { FORR(e,E[cur]) if(e!=pre) g^=G[e]; if(g==0) V.push_back(cur+1); FORR(e,E[cur]) if(e!=pre) dfs2(e,cur,g^G[e]); } void solve() { int i,j,k,l,r,x,y; string s; cin>>N; FOR(i,N-1) { cin>>x>>y; E[x-1].push_back(y-1); E[y-1].push_back(x-1); } dfs(0,0); if(G[0]) { dfs2(0,0,0); cout<<"Alice"<<endl; cout<<V.size()<<endl; sort(ALL(V)); FORR(v,V) cout<<v<<" "; cout<<endl; } else { cout<<"Bob"<<endl; } }
まとめ
トライ木を使ってMex値求めたの初めてかも。