AT2667-[AGC017D]Game on Tree【SG函数】

正题

题目链接:https://www.luogu.com.cn/problem/AT2667


题目大意

给出(n)个点的一棵树,每次可以割掉一条和根节点联通的边,轮流操作直到不能操作的输,求是否先手必胜。

(1leq nleq 2 imes 10^5)


解题思路

挺巧妙的一个东西,考虑通过每个子树的(SG)来求根的(SG)

考虑一个等价的问题就是假设我们有(k)个子树那么我们可以把根节点复制(k)份然后每个单独连接。

然后考虑我们知道了一棵树的(SG)然后往上加一个节点时新的(SG)是多少。

(DAG)来考虑的话不难发现我们其实是多了一个节点并且连向所有的状态,所以新的(SG)值加一就好连。

所以每个点子树的(SG)就等于他儿子节点子树的(SG+1)的异或和

时间复杂度(O(n))


code

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=2e5+10;
struct node{
	int to,next;
}a[N<<1];
int n,tot,ls[N],sg[N];
void addl(int x,int y){
	a[++tot].to=y;
	a[tot].next=ls[x];
	ls[x]=tot;return;
}
void dfs(int x,int fa){
	for(int i=ls[x];i;i=a[i].next){
		int y=a[i].to;
		if(y==fa)continue;
		dfs(y,x);
		sg[x]^=sg[y]+1;
	}
	return;
}
int main()
{
	scanf("%d",&n);
	for(int i=1;i<n;i++){
		int x,y;
		scanf("%d%d",&x,&y);
		addl(x,y);addl(y,x);
	}
	dfs(1,1);
	if(sg[1])puts("Alice");
	else puts("Bob");
	return 0;
}
原文地址:https://www.cnblogs.com/QuantAsk/p/14945999.html