321 树的重心
作者:互联网
视频链接:
#include <iostream> #include <cstring> #include <algorithm> #include <vector> using namespace std; const int N=100010; int n, a, b; vector<int> e[N]; int siz[N], pos, ans=1e9; void dfs(int x, int fa){ siz[x]=1; int mx=0; for(auto y : e[x]){ if(y == fa) continue; dfs(y, x); siz[x] += siz[y]; mx=max(mx, siz[y]); // printf("回%d mx=%d siz=%d\n",x,mx,siz[x]); } mx=max(mx, n-siz[x]); if(mx<ans) ans=mx,pos=x; //printf("离%d ans=%d pos=%d\n",x,ans,pos); } int main(){ scanf("%d", &n); for(int i=1;i<n;i++){ scanf("%d%d",&a,&b); e[a].push_back(b); e[b].push_back(a); } dfs(1, 0); printf("%d %d\n",pos,ans); return 0; }
标签:重心,int,siz,dfs,321,max,include,mx 来源: https://www.cnblogs.com/dx123/p/16320457.html