luoguP1395 会议

分成两部

  1. 求出树的重心
  2. \(BFS\) 求出所有点到重心的距离
#include <bits/stdc++.h>
using namespace std;
const int N = 5e4 + 10;
int e[N*2],ne[N*2],h[N],idx,rt,mds[N],ds[N],n,sum,d[N];
void add(int a,int b) {
    e[idx] = b;
    ne[idx] = h[a];
    h[a] = idx ++;
}
void dfs(int u,int fa) {
    ds[u] = 1;
    mds[u] = 0;
    for(int i = h[u];~i ;i = ne[i]) {
        int j = e[i];
        if(j == fa) continue;
        dfs(j,u);
        ds[u] += ds[j];
        mds[u] = max(mds[u],ds[j]);
    }
    mds[u] = max(mds[u],n - ds[u]);
    if(rt == 0 || mds[u] < mds[rt]) rt = u;
    if(mds[u] == mds[rt] && u < rt) rt = u;
}
void bfs() {
    queue<int> q;
    q.push(rt);
    while(q.size()) {
        int t = q.front();
        q.pop();
        for(int i = h[t]; ~i;i = ne[i]) {
            int j = e[i];
            if(d[j] || rt == j) continue;
            d[j] = d[t] + 1;
            sum += d[j];
            q.push(j);
        }
    }
}
int main() {
    memset(h,-1,sizeof h);
    cin >> n;
    for(int i = 0;i < n - 1; ++i) {
        int a,b;
        cin >> a >> b;
        add(a,b);
        add(b,a);
    }
    dfs(1,0);
    bfs();
    cout << rt << ' ' << sum << endl;
    return 0;
}
posted @ 2020-06-21 11:53  南风--  阅读(67)  评论(0编辑  收藏  举报