题目链接:http://www.rqnoj.cn/problem/331
题解:
简单的并查集应用
AC代码:
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int MAXN =5000 + 5;
int pre[MAXN];
int Find(int x) {
int r = x;
while (pre[r] != r)
r = pre[r];
int i = x, j;
while (i != r) {
j = pre[i];
pre[i] = r;
i = j;
}
return r;
}
void Join(int x, int y) {
x = Find(x);
y = Find(y);
if (x != y)
pre[x] = y;
}
int main() {
int n, m, p, x, y;
cin >> n >> m >>p;
for(int i = 0; i < n; i++) {
pre[i] = i;
}
for(int i = 0; i < m; i++) {
cin >> x >> y;
Join(x, y);
}
for(int i = 0; i < p; i++) {
cin >> x >> y;
if(Find(x) == Find(y)) {
cout << "Yes" << endl;
}
else {
cout << "No" << endl;
}
}
return 0;
}