P1551 亲戚 (并查集 入门题) C++


题目描述

链接
在这里插入图片描述

思路

参考 我的并查集模板 笔记

代码1

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;//数据太大 要开ll
const int N = 100010;
int p[N];

int find(int x) {
    
    
    if(p[x] != x) {
    
    
        p[x] = find(p[x]);
    }
    return p[x];
}

int main () {
    
    
    int n, m, x;
    cin >> n >> m >> x;
    for (int i = 1; i <= n; i ++) {
    
    
        p[i] = i;
    }
    while (m --) {
    
    
        int a, b;
        cin >> a >> b;
        p[find(a)] = find(b);
    }
    while (x --) {
    
    
        int a, b;
        cin >> a >> b;
        if(find(a) == find (b)) {
    
    
            puts("Yes");
        } else {
    
    
            puts("No");
        }
    }
     return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_49486457/article/details/123972888