并查集(不带权 + 带权)

本文介绍了两种类型的并查集:不带权重并查集与带权重并查集,并提供了详细的实现代码,包括初始化、查找和合并操作。对于带权重并查集,还特别解释了如何维护节点之间的关系。

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

1. 不带权重并查集

三个操作: 初始化, 查找, 合并.
#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
const int MAX_SIZE=1002;
int Set_father[MAX_SIZE];
int Set_Count[MAX_SIZE];

void Initialization(){
    num=0;
    for(int i = 0; i < MAX_SIZE; ++i){
        Set_father[i]=i;
        Set_Count[i]=0;
    }
}
int find(int p){
    if(p==Set_father[p]){
        return Set_father[p];
    }
    return Set_father[p]=find(Set_father[p]);
}
void Union(int a,int b){
    int x,y;
    x=find(a);
    y=find(b);
    if(x!=y){
        Set_father[y]=x;
    }
}

2. 带权重并查集

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int SIZE = 650;
const int maxn = 2100;

struct node{
    int father;
    int relation; //表示和父类的关系 一般分为三种, 分别用0, 1, 2 表示. 这样就可以用对3的模来计算并查集中的关系
}pic[SIZE];
int mark[SIZE];

void init(){
    for(int i = 0; i < SIZE; ++i){
        pic[i].father = i;
        pic[i].relation = 0;
    } 
} 

int find(int p){
    if(p == pic[p].father){
        return p;
    }else{
        int x = pic[p].father;
        pic[p].father = find(pic[p].father);
        pic[p].relation = (pic[p].relation + pic[x].relation) % 3; //对于关系的更新操作
        return pic[p].father;
    }
}

void Union(int a, int b, int val) // val表示关系
{
    int x = find(a);
    int y = find(b);

    if(x == y){
        int r = (pic[b].relation - pic[a].relation + 3) % 3; //对于关系的合并
    }else{
        pic[y].father = x;
        pic[y].relation = (pic[a].relation - pic[b].relation + c +3)%3; // 合并关系
        }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值