寒假集训并查集初级版

#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
const int maxn = 105;

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

/*void Merge(int a,int b){
    fa[find(a)] = find(b);//低配版Merge只能将前者归并到后者可能会增加深度
}*/

void Merge(int a,int b){
    int rx = find(a),ry = find(b);
    if(height[rx] < height[ry])fa[rx] = ry;
    else fa[ry] = rx;
    if(height[rx] == height[ry] && rx != ry)height[rx]++;//将rx的父亲设为ry,即归并rx到ry,深度加1
}//精进版(其实也差不多少,因为路径压缩已经将单步复杂度均摊到O(1)了),主要精进在而已尽可能的使树的深度较小

int main(){
    int n;
    scanf("%d",&n);
    for(int i = 1;i <= n;++i)fa[i] = i;//初始化每个节点的父节点为自己
    //然后加上一堆查找添加;
    return 0;
}
//这个简单的一批的单纯的路径压缩就打完了

原文地址:https://www.cnblogs.com/2004-08-20/p/12302555.html