[Algorithm Fundamentals] 837. Number of Points in Connected Blocks (Graph Theory + Union Search)

insert image description here


Topic description

topic link
insert image description here

ideas

if(find(a) == find(b)) continue;
siz[find(b)] += siz[find(a)];//在根节点上加上另一个树节点的古树
p[find(a)] = find(b);

Think of a connected block as a set, and open an sizarray to record the number of nodes of the two connected blocks. The two connected blocks are merged, that is, the two sizarrays can be added, but they must be added to the parent node. Note that the order is First add the root node, update the parent node, and if a,bit is in the same connected block, there is no need to insert the operation, directlycontinue
insert image description here

code 1

#include <bits/stdc++.h>
using namespace std ;
const int N = 100010;
int n, m;
int siz[N], p[N];

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

int main () {
    
    
    cin >> n >> m;
    for (int i = 1; i <= n; i++) {
    
    
        p[i] = i;
        siz[i] = 1;
    }
    char op[5];
    while (m --) {
    
    
        cin >> op;
        int a, b;
        if(op[0] == 'C') {
    
    
            cin >> a >> b;
            if(find(a) == find(b)) continue;
            siz[find(b)] += siz[find(a)];//在根节点上加上另一个树节点的古树
            p[find(a)] = find(b);
        } else if(op[1] == '1') {
    
    
            cin >> a >> b;
            if(find(a) == find(b)) {
    
    
                puts("Yes");
            } else {
    
    
                puts("No");
            }
        } else {
    
    
            cin >> a;
            cout << siz[find(a)] << endl;
        }
    }
    return 0;
}

Guess you like

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