CF685B Kay and Snowflake 贪心

CF685B Kay and Snowflake

链接

CF

题目大意

给你一颗树,询问子树的重心

思路

贪心?
重心肯定是向上走的,所以直接向上跳就好了。
不优秀的时候就不要跳了 ,因为以后也不能更新了。
复杂度O(n)(没大仔细想过)

代码

#include <bits/stdc++.h>
using namespace std;
const int N=3e5+7;
int read() {
	int x=0,f=1;char s=getchar();
	for(;s>'9'||s<'0';s=getchar()) if(s=='-') f=-1;
	for(;s>='0'&&s<='9';s=getchar()) x=x*10+s-'0';
	return x*f;
}
vector<int> G[N];
int n,m,siz[N],ans[N],fa[N],ma[N];
void dfs_siz(int u) {
	siz[u]++;
	for(vector<int>::iterator v=G[u].begin();v!=G[u].end();++v) {
		dfs_siz(*v);
		siz[u]+=siz[*v];	
		ma[u]=max(ma[u],siz[*v]);
	}
}
void dfs(int u) {
	ans[u]=u;
	for(vector<int>::iterator v=G[u].begin();v!=G[u].end();++v) {
		dfs(*v);
		int tmp=ans[*v],now=ma[u];
		while(tmp!=u) {
			if(max(ma[tmp],siz[u]-siz[tmp]) < now) {
				now=max(ma[tmp],siz[u]-siz[tmp]);
				ans[u]=tmp;
			}
			if(ma[tmp]>siz[u]-siz[tmp]) break;
			tmp=fa[tmp];
		}
	}
}
int main() {
	// freopen("a.in","r",stdin);
	n=read(),m=read();
	for(int i=2;i<=n;++i) {
		fa[i]=read();
		G[fa[i]].push_back(i);
	}
	dfs_siz(1);
	dfs(1);
	for(int i=1;i<=m;++i) printf("%d
",ans[read()]);
	return 0;
}
原文地址:https://www.cnblogs.com/dsrdsr/p/10783349.html