P1551 Relatives (and check set entry questions) C++


Topic description

Link
insert image description here

ideas

Refer to my union template notes

code 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;
}

Guess you like

Origin blog.csdn.net/weixin_49486457/article/details/123972888