并查集模板 hdu-1213

本文介绍了并查集数据结构的优化方法,包括合并操作的优化,通过比较根节点高度来减小树的高度,以及查询的优化——路径压缩,使得查找元素所属集合的时间复杂度降低。最后给出了优化后的完整代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

 

例题:hdu 1213​

1、合并的优化

2、查询的优化——路径的压缩

3、优化完成的代码为:


例题:hdu 1213

//#include <bits/stdc++.h>
#include <iostream>
#include <stack>
#include <string>
#include <queue>
#include <stack>
#include <set>
#include <list>
#include <map>
#include <algorithm>
#include <string.h>
using namespace std;

const int MAXN = 1005;
int s[MAXN];
void init_set(){
    for(int i = 1; i <= MAXN; i++)
        s[i] = i;
}

int find_set(int x){
    return x = s[x]? x: find_set(s[x]);
}

void union_set(int x, int y){
    x = find_set(x);
    y = find_set(y);
    if(x != y) s[x] = s[y];
}

int main(){
    int t, n, m, x, y;
    cin >> t;
    while(t--){
        cin >> n >> m;
      
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值