【BZOJ】【P1131】【POI2008】【Sta】【题解】【dfs+bfs】

传送门:http://www.lydsy.com/JudgeOnline/problem.php?id=1131

先随便找个点做根计算dep,size,depsum

然后

depsum[u]=depsum[fa[u]]-siz[u]+(n-siz[u])

bfs递推即可

Code:

#include<cstdio> 
#include<queue>
#include<cctype>
#include<numeric>
#include<vector>
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn=1e6+5;
int n;
vector<int>G[maxn];
int siz[maxn],dep[maxn],fa[maxn];
typedef long long LL;
LL depsum[maxn];
void dfs(int u){
	siz[u]=1;
	for(int i=0,v;i<G[u].size();i++){
		if((v=G[u][i])!=fa[u]){
			fa[v]=u;
			dep[v]=dep[u]+1;
			dfs(v);
			siz[u]+=siz[v];
		}		
	}
}
queue<int>q;
int getint(){
	int res=0;char c=getchar();
	while(!isdigit(c))c=getchar();
	while(isdigit(c))res=res*10+c-'0',c=getchar();
	return res;
}
int main(){
	n=getint();
	for(int i=1;i<n;i++){
		int u=getint(),v=getint();
		G[u].push_back(v);G[v].push_back(u);		
	}dfs(1);
	depsum[1]=accumulate(dep+1,dep+1+n,0LL);
	q.push(1);
	while(!q.empty()){
		int u=q.front();q.pop();
		for(int i=0,v;i<G[u].size();i++){
			if((v=G[u][i])!=fa[u]){
				depsum[v]=depsum[u]-siz[v]+(n-siz[v]);
				q.push(v);
			}
		}
	}cout<<max_element(depsum+1,depsum+1+n)-depsum<<endl;
	return 0;
}


你可能感兴趣的:(bzoj)