AcWing 846:树的重心 ← 类似“东方博宜OJ 2190:树的重心”代码

【题目来源】
https://www.acwing.com/problem/content/848/

【问题描述】
给定一颗树,树中包含 n 个结点(编号 1∼n)和 n−1 条无向边。
请你找到树的重心,并输出将重心删除后,剩余各个连通块中点数的最大值。
重心定义:重心是指树中的一个结点,如果将这个点删除后,剩余各个连通块中点数的最大值最小,那么这个节点被称为树的重心。

【输入格式】
第一行包含整数 n,表示树的结点数。
接下来 n−1 行,每行包含两个整数 a 和 b,表示点 a 和点 b 之间存在一条边。

【输出格式】
输出一个整数 m,表示将重心删除后,剩余各个连通块中点数的最大值。

【数据范围】
1≤n≤10^5

【输入样例】
9
1 2
1 7
1 4
2 8
2 5
4 3
3 9
4 6

【输出样例】
4

【算法分析】
● 链式前向星:https://blog.csdn.net/hnjzsyjyj/article/details/139369904

【算法代码:链式前向星
本文代码与“东方博宜OJ 2190:树的重心”代码的差别,仅在于 dfs 函数的最后部分不同。
详见:https://blog.csdn.net/hnjzsyjyj/article/details/155821553

#include <bits/stdc++.h>
using namespace std;

const int N=1e5+5;
const int M=N<<1;
int h[N],e[M],ne[M],idx;
int cnt[N],dis[N];
int n,cr; //core
int imax=INT_MAX;

void add(int a,int b) {
    e[idx]=b,ne[idx]=h[a],h[a]=idx++;
}

void dfs(int u,int fa) {
    cnt[u]=1;
    int rem=0; //remnant
    for(int i=h[u]; i!=-1; i=ne[i]) {
        int j=e[i];
        if(j==fa) continue;
        dfs(j,u);
        cnt[u]+=cnt[j];
        rem=max(rem,cnt[j]);
    }
    rem=max(rem,n-cnt[u]);
    dis[u]=rem;
    imax=min(imax,rem);
}

int main() {
    memset(h,-1,sizeof h);
    cin>>n;
    for(int i=1; i<n; i++) {
        int a,b;
        cin>>a>>b;
        add(a,b),add(b,a);
    }

    dfs(1,-1);
    cout<<imax<<endl;

    return 0;
}

/*
in:
9
1 2
1 7
1 4
2 8
2 5
4 3
3 9
4 6

out:
4
*/





【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/155821553
https://www.acwing.com/solution/content/287387/
https://blog.csdn.net/hnjzsyjyj/article/details/139369904
https://blog.csdn.net/hnjzsyjyj/article/details/108655516
https://blog.csdn.net/qq_47783057/article/details/116195481
https://www.acwing.com/solution/content/13513/
https://www.acwing.com/solution/content/4917/

 

 

 

posted @ 2025-12-11 23:16  Triwa  阅读(1)  评论(0)    收藏  举报