并查集模板

并查集

概念

并查集是一种简单的集合表示,支持2种操作:

  1. 查找集合S中元素x所在子集合,并返回子集合名字。
  2. 把集合S中子集合root2并入子集合root1,要求2集合互不相交。

通常用森林的双亲作为并查集的存储结构,每个集合以一棵树表示。

模板

#include <iostream>
#include <vector>
using namespace std;

typedef int ElementType;
struct Set
{
    ElementType data;
    int parent;
};

// 查找某个元素所在集合(用根结点表示)
int Find(vector<Set> &S, ElementType x)
{
    int i;
    for (i = 0; i < S.size() && S[i].data != x; i++)
    {
        ;
    }
    if (i >= S.size())
    {
        return -1;
    }
    for (; S[i].parent >= 0; i = S[i].parent)
    {
        ;
    }
    return i;
}

// 集合并操作
void Union(vector<Set> &S, ElementType x1, ElementType x2)
{
    int root1, root2;
    root1 = Find(S, x1);
    root2 = Find(S, x2);
    if (root1 != root2)
    {
        S[root2].parent = root1;
    }
}

int main()
{
    vector<Set> S(10);
    // Parent
    // -1 0 -1 0 2 -1 0 2 5 5
    for (int i = 0; i < 10; i++)
    {
        S[i].data = i + 1;
        int tmp;
        cin >> tmp;
        S[i].parent = tmp;
    }
    Union(S, 10, 5);
    for (auto it : S)
    {
        cout << it.data << " " << it.parent << endl;
    }
    system("pause");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值