前言:
洛谷P1551亲戚,题主用的并查集
题目描述:
思路:
见代码
AC代码:
#include <iostream>
#include <algorithm>
using namespace std;
struct in {
int x;
int y;
}a[5005];
int n, m, p;
int pre[5005];
//经典寻找祖先
int find(int x) {
//如果它前面一位是它本身,证明他是根源
if (x == pre[x]) {
return x;
}
//否则就让它直接连接在根源祖先上
//减少以后查找时的递归次数
return pre[x] = find(pre[x]);
}
int main() {
std::ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n >> m >> p;
//先对pre进行初始化
for (int i = 1; i <= n; i++) {
pre[i] = i;
}
for (int i = 1; i <= m; i++) {
cin >> a[i].x >> a[i].y;
//如果二者没有共同的祖先,就让二者联通,一直到有共同的祖先为止
while (find(a[i].x) != find(a[i].y)) {
pre[find(a[i].x)] = find(a[i].y);
}
}
int s, t;
for (int i = 1; i <= p; i++) {
cin >> s >> t;
//判断二者是否有共同的选择
if (find(s)==find(t)) {
cout << "Yes" << endl;
}
else {
cout << "No" << endl;
}
}
}