简易的并查集

#include<bits/stdc++.h>
using namespace std;

/*
    简易版的并查集:
        集合的元素使用数组的下标。集合的数据是它的父结点 
*/

int getRoot(int *parent, int x)
{
    if(parent[x] < 0)
        return x;
    return parent[x] = getRoot(parent, parent[x]);
}

void unionSets(int *parent, int x, int y)
{
    int rx = getRoot(parent, x);
    int ry = getRoot(parent, y);
    if(parent[rx] < parent[ry])
    {
        parent[rx] += parent[ry];
        parent[ry] = rx;
    }else{
        parent[ry] += parent[rx];
        parent[rx] = ry;
    }
}

int main()
{
    int arr[6] = {-3, 0, 1, 2, -1, 4};
    cout << getRoot(arr, 3) << endl;
    cout << getRoot(arr, 5) << endl;
    unionSets(arr, 3, 5);
    cout << getRoot(arr, 5) << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_38206090/article/details/82228417
今日推荐