东方博宜OJ 4567:树的根 ← 并查集

【题目来源】
https://oj.czos.cn/p/4567

【题目描述】
一棵有 N 个结点的树,树上结点编号为 1 到 N。
已知树上 N-1 条边,且已知每条边的父子关系。
请编程求出树上根结点的编号。

【输入格式】
第 1 行输入一个整数 N 代表树上结点的数量。(1≤N≤100)。
接下来 N-1 行,每行输入两个整数 X,Y,代表编号为 X 的结点是编号为 Y 的结点的父。

【输出格式】
输出一个整数,代表树上根结点的编号。​​​​​​​

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

【输出样例】
3

【数据范围】
1≤N≤100​​​​​​​

【算法分析】
● 找根的算法思想一:遍历所有节点,直至父节点为空的节点,即为根。详见:https://blog.csdn.net/hnjzsyjyj/article/details/155789364

● 找根的算法思想二:并查集 → https://blog.csdn.net/hnjzsyjyj/article/details/146941814
注意,在此题并查集 merge 函数的声明中,是 pre[b]=a,而不是 pre[a]=b。

【算法代码:并查集

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

const int maxn=1e2+5;
int pre[maxn];

int find(int x) {
    if(x!=pre[x]) pre[x]=find(pre[x]);
    return pre[x];
}

void merge(int x,int y) {
    int a=find(x);
    int b=find(y);
    if(a!=b) pre[b]=a;
}

int main() {
    int n,x,y;
    cin>>n;
    for(int i=1; i<=n; i++) pre[i]=i;
    for(int i=1; i<n; i++) {
        cin>>x>>y;
        merge(x,y);
    }

    for(int i=1; i<=n; i++) {
        if(pre[i]==i) cout<<i<<endl;
    }

    return 0;
}

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

out:
3
*/

 
 



【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/155789364
https://blog.csdn.net/hnjzsyjyj/article/details/155763839
https://blog.csdn.net/hnjzsyjyj/article/details/140138335
 

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