Disjoint-set (UnionFind)

Nature

Query two elements belong to the same class

Compare the image of the relatives, A is the father of B, B is C's father, asked whether there is relationship between A and C;

Can also be a city road, 1,2,3 three cities, roads 1-- 2,2 - 3, Q 1 3 city can reach the city;

Sample

The first line contains two integers N, M, N represents a total of M elements and operations.

Next M rows, each row containing three integers Zi, Xi, Yi

When Zi = 1, the combined set of Xi and Yi where

When Zi = 2, the output Xi and Yi are in the same set, it is if the Y output; otherwise, if the output N;

4 7
2 1 2
1 1 2
2 1 2
1 3 4
2 1 4
1 2 3
2 1 4

Naive Code

#include <bits/stdc++.h>

using namespace std;

const int N = 100001;

int n,m;
int fa[N];

int find(int x){
    return fa[x] == x ? x : find(fa[x]);
}

void uni(int x, int y){
    fa[find(x)] = find(y);
}

int ask(int x, int y){
    return find(x) == find(y);
}
int main(){
    cin >> n >> m;
    for(int i = 1; i <= n; ++i) fa[i] = i; // 最开始只和自己有关系
    for(int i = 1, x, y, z; i <= m; ++i){
        cin >> z >> x >> y;
        if(z == 1) uni(x, y);
        else ask(x, y) == true ? printf("Y\n") : printf("N\n");
    }
    return 0;
}

 optimization

  1. By rank merger
  2. Path compression

Path compression

If we only think of their ancestors, without regard to the specific relationship between the individual, you can find an optimization function in Riga

Code

int find(int x){
    return fa[x] == x ? x : fa[x] = find(fa[x]);
}

 

Guess you like

Origin www.cnblogs.com/Adventurer-H/p/11224896.html