树的直径与重心

树的直径与重心

直径

重心

定义

最大子树最小的节点

性质

性质1:“树中所有点到某个点的距离和中,到重心的距离和是最小的
性质2:把两棵树通过一条边相连,新的树的重心在原来两棵树重心的连线上。
性质3: 一棵树添加或者删除一个节点,树的重心最多只移动一条边的位置。
性质4: 一棵树最多有两个重心,且相邻。

算法

每次找到一个节点的最大子树更新ans,一个节点的子树包括指向的子树与减去当前节点子树后剩下的部分。

例题

Luogu-P1395

#include <iostream>
#include <cstdio>
#include <cmath>
#include <queue>
#include <map>
#include <cstring>
#include <algorithm>
#define rint register int
#define ll long long
using namespace std;
template <typename xxx> inline void read(xxx &x)
{
    int f = 1;x = 0;
    char c = getchar();
    for(; c < '0' || c > '9' ; c = getchar()) if(c=='-') f = -1;
    for(;'0' <= c && c <= '9'; c = getchar()) x = (x << 3) + (x << 1) + (c ^ 48);
    x *= f;
}
template <typename xxx> inline void print(xxx x)
{
    if(x < 0) {
        putchar('-');
        x = -x;
    }
    if(x > 9) print(x/10);
    putchar(x % 10 + '0');
}
const int inf = 0x7fffffff;
const int maxn = 100200;
const int mod = 2015;
struct edge{
    int to,last;
}e[maxn];
int head[maxn],tot;
inline void add(int from,int to) {
    ++tot;
    e[tot].to = to;
    e[tot].last = head[from];
    head[from] = tot;
}   
int n,ans = inf,rt = 1;
int siz[maxn],dis[maxn];
inline void ddfs(int x,int fa){
    siz[x] = 1;int ret = 0;
    for(rint i = head[x]; i; i = e[i].last) {
        if(e[i].to == fa) continue;
        ddfs(e[i].to,x);
        siz[x] += siz[e[i].to];
        ret = max(ret,siz[e[i].to]);
    }
    ret = max(ret,n - siz[x]);
    if(ret < ans) {
        ans = ret;
        rt = x;
    }
    else if(ret == ans && rt > x) rt = x;
    return ;
}
inline void fk(int x,int fa) {
    dis[x] = dis[fa] + 1;
    for(rint i = head[x];i;i = e[i].last) {
        if(e[i].to == fa) continue;
        fk(e[i].to,x);
    }
}
int main()
{
    read(n);
    for(rint i = 2;i <= n; ++i) {
        int a,b;
        read(a);read(b);
        add(a,b);add(b,a);
    }
    dis[0] = -1;
    ddfs(1,0);fk(rt,0);
    int tem = 0;
    for(rint i = 1;i <= n; ++i) tem += dis[i];
    print(rt);putchar(' ');print(tem);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/Thomastine/p/11746098.html