46 lines
1.2 KiB
C++
46 lines
1.2 KiB
C++
#include <bits/stdc++.h>
|
||
|
||
using namespace std;
|
||
|
||
const int N = 5010;
|
||
|
||
int n; //n个人
|
||
int m; //m个亲戚
|
||
int p; //询问p对亲戚关系
|
||
int x, y; //输入两个人之间的关系
|
||
int fa[N]; //并查集数组
|
||
|
||
//要深入理解这个递归并压缩的过程
|
||
int find(int x) {
|
||
if (fa[x] != x)//如果x不是族长,递归找父亲,副产品就是找回的结果更新掉自己的家族信息。
|
||
fa[x] = find(fa[x]);//非常经典的更新,路径压缩大法!
|
||
//返回族长是谁
|
||
return fa[x];
|
||
}
|
||
|
||
|
||
//加入家族集合中
|
||
void join(int c1, int c2) {
|
||
int f1 = find(c1), f2 = find(c2);
|
||
if (f1 != f2)fa[f1] = f2;//各自找家长,如果家长不一样,就把C1的族长,认C2的族长为爸爸,C1的族长强烈表示不满意
|
||
}
|
||
|
||
int main() {
|
||
cin >> n >> m >> p;
|
||
//并查集初始化
|
||
for (int i = 1; i <= n; i++)fa[i] = i; //自己是自己的老大
|
||
|
||
//录入m种关系
|
||
for (int i = 1; i <= m; i++) {
|
||
cin >> x >> y;
|
||
//加入并查集
|
||
join(x, y);
|
||
}
|
||
//处理p次询问
|
||
while (p--) {
|
||
cin >> x >> y;
|
||
if (find(x) == find(y)) cout << "Yes" << endl;
|
||
else cout << "No" << endl;
|
||
}
|
||
return 0;
|
||
} |