CF767C Garland

LVIII.CF767C Garland

有两种可行方法:

  1. 对于一个点,它存在两个儿子,使得这两个儿子的子树中个存在一棵子树,它们的\(size\)都是\(1/3\)

  2. 对于一个点,它的\(size\)\(2/3\),并且它的子树中存在一个子树,它的\(size\)\(1/3\)

然后我们只需要对于每个节点记录\(has1[x]\)表示子树中是否有一个\(size=1/3\)的节点即可。复杂度\(O(n)\)

代码:

#include<bits/stdc++.h>
using namespace std;
int n,rt,head[1001000],sum[1001000],all,val[1001000],cnt,has1[1001000];
struct node{
	int to,next;
}edge[1001000];
void ae(int u,int v){
	edge[cnt].next=head[u],edge[cnt].to=v,head[u]=cnt++;
}
void dfs(int x){
	sum[x]=val[x];
	for(int i=head[x];i!=-1;i=edge[i].next){
		dfs(edge[i].to),sum[x]+=sum[edge[i].to];
		if(has1[edge[i].to]){
			if(!has1[x])has1[x]=has1[edge[i].to];
			else{printf("%d %d\n",has1[x],has1[edge[i].to]);exit(0);}
		}
	}
	if(sum[x]==all*2&&has1[x]&&x!=rt){printf("%d %d\n",x,has1[x]);exit(0);}
	if(sum[x]==all)has1[x]=x;
}
int main(){
	scanf("%d",&n),memset(head,-1,sizeof(head));
	for(int i=1,x;i<=n;i++){
		scanf("%d%d",&x,&val[i]),all+=val[i];
		if(!x)rt=i;
		else ae(x,i);
	}
	if(all%3!=0){puts("-1");return 0;}
	all/=3;
	dfs(rt);
	puts("-1");
	return 0;
}

原文地址:https://www.cnblogs.com/Troverld/p/14597469.html