并查集模板

本文通过一个HDU1213题目详细解释了并查集(Disjoint Set Union, DSU)的数据结构及其优化——路径压缩。代码中展示了如何初始化、查找根节点、合并集合以及优化后的合并操作。并查集常用于解决不相交集合的问题,此例中用于统计给定边连接的不相交子树数量。
摘要由CSDN通过智能技术生成
//#include <bits/stdc++.h>
#include <iostream>
using namespace std;
const int N = 1010;
int b[N+1];

void init()
{//初始化
    for(int i=1; i<=N; i++) {
        b[i] = i;
    }
}

int find_set(int x)
{//查找
    if(x != b[x]) b[x] = find_set(b[x]);
    return b[x];
}

int find_plus(int x)
{//非递归查找
    int r = x;
    while(r != b[r]) r = b[r];//查找根节点
    
    int i = x, j;
    while(i != r) {
        j = b[i];
        b[i] = r;//把路径上元素的集改为根节点
        i = j;
    }
    
    return r;
}

void union_set(int x, int y)
{//合并
    x = find_set(x); y = find_set(y);
    if(x != y) b[x] = b[y];
}

int h[N+1];
void union_plus(int x, int y)
{//优化合并
    x = find_set(x); y = find_set(y);
    if(h[x] == h[y]) {
        h[x] = h[x] + 1;//合并,数高加1
        b[y] = x;
    }
    else {
        if(h[x] < h[y]) b[x] = y;//矮树并高树
        else b[y] = x;
    }
}

///hdu1213 题板
int main()
{
    int t; cin >> t;
    while(t--) {
        init();
        int n, m; cin >> n >> m;
        for(int i=1; i<=m; i++) {
            int l, r; cin >> l >> r;
            //if(b[find_set(l)] != b[find_set(r)]) 
                union_set(l, r);
        }
        
        int ans = 0;//统计并查集数列
        for(int i=1; i<=n; i++) {
            if(b[i] == i) ans++;
        }
        cout << ans << endl;
    }
    return 0;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值