Use map to realize and check collection

Generally, the father uses an array, but it is not applicable when the total number of nodes is not known and the node numbers are not continuous. You can use map

#include <cstdio>
#include <unordered_map>

using namespace std;

unordered_map<int, int> father;

int findFather(int v);
void unionSet(int i, int j);

int main(){
    
    
    int i, j;
    while(scanf("%d%d", &i, &j)!=EOF){
    
    
        unionSet(i, j);
    }
    int ans = 0;
    for(auto it=father.begin(); it!=father.end(); it++){
    
    
        if(it->first == it->second) ans++;
    }
    printf("%d", ans);
    return 0;
}

int findFather(int v){
    
    
    if(father.count(v)>0){
    
    
        int x = v;
        while(v != father[v]) v = father[v];
        while(x != v){
    
    
            int temp = father[x];
            father[x] = v;
            x = temp;
        }
    }
    else father[v] = v; //initialize a new node
    return v;
}

void unionSet(int i, int j){
    
    
    int fi = findFather(i), fj = findFather(j);
    if(fi != fj) father[fj] = fi;
    return;
}

Guess you like

Origin blog.csdn.net/sinat_37517996/article/details/105455654