洛谷 P1551:亲戚 ← 基础并查集
【题目来源】
https://www.luogu.com.cn/problem/P1551
【题目背景】
若某个家族人员过于庞大,要判断两个是否是亲戚,确实还很不容易,现在给出某个亲戚关系图,求任意给出的两个人是否具有亲戚关系。
【题目描述】
规定:x 和 y 是亲戚,y 和 z 是亲戚,那么 x 和 z 也是亲戚。如果 x,y 是亲戚,那么 x 的亲戚都是 y 的亲戚,y 的亲戚也都是 x 的亲戚。
【输入格式】
第一行:三个整数 n,m,p,(n,m,p≤5000),分别表示有 n 个人,m 个亲戚关系,询问 p 对亲戚关系。
以下 m 行:每行两个数 Mi,Mj,1≤Mi,Mj≤n,表示 Mi 和 Mj 具有亲戚关系。
接下来 p 行:每行两个数 Pi,Pj,询问 Pi 和 Pj 是否具有亲戚关系。
【输出格式】
p 行,每行一个 Yes 或 No。表示第 i 个询问的答案为“具有”或“不具有”亲戚关系。
【输入样例】
6 5 3
1 2
1 5
3 4
5 2
1 3
1 4
2 3
5 6
【输出样例】
Yes
Yes
No
【算法分析】
并查集(Union-Find Set)是一种树型数据结构,专用于处理不相交集合的合并与查询问题。
【算法代码】
#include <bits/stdc++.h>
using namespace std;
const int maxn=5e3+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[a]=b;
}
int main() {
int n,m,p;
cin>>n>>m>>p;
for(int i=1; i<=n; i++) {
pre[i]=i;
}
int x,y;
for(int i=1; i<=m; i++) {
cin>>x>>y;
merge(x,y);
}
int u,v;
while(p--) {
cin>>u>>v;
if(find(u)==find(v)) cout<<"Yes"<<endl;
else cout<<"No"<<endl;
}
return 0;
}
/*
in:
6 5 3
1 2
1 5
3 4
5 2
1 3
1 4
2 3
5 6
out:
Yes
Yes
No
*/
【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/120120591
https://blog.csdn.net/hnjzsyjyj/article/details/120131297
https://blog.csdn.net/hnjzsyjyj/article/details/126455868
更多推荐




所有评论(0)