题目链接:https://vijos.org/problems/P1034并查集入门题 view code 1 #include <iostream> 2 #include <cstdio> 3 #include <cstdlib> 4 #include <cstring> 5 #include <cmath> 6 #include <algorithm> 7 using namespace std; 8 #define N 5010 9 int p[N]; 10 int find(int x) 11 { 12 return p[x] != x ? p[x] = find(p[x]) : x; 13 } 14 int main() 15 { 16 int n, m, q; 17 int x, y, r1, r2; 18 scanf("%d%d%d", &n, &m, &q); 19 for (int i = 1; i <= n; i++) p[i] = i; 20 for (int i = 1; i <= m; i++) 21 { 22 scanf("%d%d", &x, &y); 23 r1 = find(x); r2 = find(y); 24 if (r1 != r2) p[r2] = r1; 25 } 26 for (int i = 1; i <= q; i++) 27 { 28 scanf("%d%d", &x, &y); 29 r1 = find(x); r2 = find(y); 30 if (r1 == r2) printf("Yes\n"); 31 else printf("No\n"); 32 } 33 return 0; 34
|