B07 DFS 树的重心
视频链接:E32 树形DP 树的重心_哔哩哔哩_bilibili
#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]); } mx=max(mx, n-siz[x]); if(mx<ans) ans=mx,pos=x; } 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; }