并查集模板

//#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、付费专栏及课程。

余额充值