并查集:
并就是合并
查就是查找
集就是集合
总而言之:合并集合,查找集合
为了方便将两个数字的集合合并
为了方便判断两个数字是否属于同一集合
#include<iostream>
using namespace std;
int a[5005];
int find(int i) {
if (a[i] == 0) return i;//初始化(a[0]=0,a[1]=1)
return a[i] = find(a[i]);//查找父节点(不断找父节点)
}
void bcj(int x, int y) {
int x1 = find(x), y1 = find(y);//寻找父节点
if (x1 != y1)
a[y1] = x1;//x1为父, y1为子
}//即x的父类指向y1的父类
int main() {
int z, x, y;
int n, m, p;
cin >> n >> m >> p;
for (int i = 0;i < m;i++) {
cin >> x >> y;
bcj(x, y);//并集
}
for (int i = 0;i < p;i++) {
cin >> x >> y;
cout << find(x) << " " << find(y) << endl;
if (find(x) == find(y))//即有共同节点
cout << "Yes" << endl;
else cout << "No" << endl;
}
return 0;
}