[經典算法]並查集


概述:

並查集(Union-find Sets)是一種非常精巧而實用的數據結構,它主要用於處理一些不相交集合的合並問題。一些常見的用途有求連通子圖、求最小生成樹的 Kruskal 算法和求最近公共祖先(Least Common Ancestors, LCA)等。

使用並查集時,首先會存在一組不相交的動態集合 S={S1,S2,⋯,Sk},一般都會使用一個整數表示集合中的一個元素。

每個集合可能包含一個或多個元素,並選出集合中的某個元素作為代表。每個集合中具體包含了哪些元素是不關心的,具體選擇哪個元素作為代表一般也是不關心的。我們關心的是,對於給定的元素,可以很快的找到這個元素所在的集合(的代表),以及合並兩個元素所在的集合,而且這些操作的時間復雜度都是常數級的。

 

程序代碼:

#include <gtest/gtest.h>
#include <vector>

using namespace std;

class UnionFindSet
{
public:
    void MakeSet(int max)
    {
        m_vecId.assign(max,0);
        for (int i=0; i<max; i++)
        {
            m_vecId[i] = i;
        }

        m_nSetsCount = max;
    }

    int Find(int x)
    {
        return m_vecId[x];
    }

    void UnionSet(int x, int y)
    {
        int xId = Find(x);
        int yId = Find(y);

        if (xId == yId)
        {
            return;
        }

        for (unsigned int i=0; i<m_vecId.size(); ++i)
        {
            if (m_vecId[i] == xId)
            {
                m_vecId[i] = yId;
            }
        }

        --m_nSetsCount;
    }

    int Count()
    {
        return m_nSetsCount;
    }

    bool SameSet(int x, int y)
    {
        return (Find(x) == Find(y));
    }

private:

    vector<int> m_vecId;
    int m_nSetsCount;
};

TEST(Algo, tUnionFindSet)
{
    // 測試集合,按照字母大小寫來區分
    char SetData[] = {'A','b','C','E','d','e','F'};

    UnionFindSet uf;
    uf.MakeSet(7);

    uf.UnionSet(0,2); // A C
    uf.UnionSet(2,3); // C E
    uf.UnionSet(3,6); // E F

    uf.UnionSet(1,4); // b d
    uf.UnionSet(4,5); // d e

    ASSERT_TRUE(uf.SameSet(0,3));
    ASSERT_TRUE(uf.SameSet(6,2));
    ASSERT_TRUE(uf.SameSet(1,5));

    ASSERT_FALSE(uf.SameSet(0,5));
    ASSERT_FALSE(uf.SameSet(2,1));
    ASSERT_FALSE(uf.SameSet(6,4));
}

 

參考引用:

http://www.cnblogs.com/cyjb/p/UnionFindSets.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM