【數據結構】77_Kruskal 算法生成最小生成樹

最小生成樹的特徵

  • 選取的邊是圖中權值較小的邊
  • 全部邊鏈接後不構成迴路

image.png

問題

既然最小生成樹關心的是如何選擇 n-1 條邊,那麼是否能夠直接以邊爲核心進行算法設計?

簡單嘗試

由 4 個頂點構成的圖,選擇 3 條權值最小的邊

image.png

須要解決的問題

如何判斷 新選擇的邊與已選擇的邊是否構成迴路?

image.png

產生迴路:
image.pngios

技巧:前驅標記數組

  • 定義數組: Array<int> p(vCount());
  • 數組元素的定義:算法

    • p[n] 表示頂點 n 在邊的鏈接通路上的另外一端頂點

image.png

示例分析:使用標記數組選擇邊

1_meitu_1.jpg

2_meitu_2.jpg

3_meitu_3.jpg

迴路邊時:

4_meitu_4.jpg

最小生成樹算法的核心步驟(Kruskal)

  • 定義前驅標記數組: Array<int> p(vCount())
  • 獲取當前圖中的全部邊,並保存於 edges 數組中
  • 對數組 edges 按照權值進行排序
  • 利用 p 數組在 edges 數組選擇前 n-1 不構成迴路的邊

Kruskal 算法流程

image.png

關鍵的 find 查找函數

int find(Array<int> &p, int v)
{
    while (p[v] != -1)
    {
        v = p[v];
    }
    
    return v;
}

編程實驗:最小生成樹算法

文件:Graph.h編程

#ifndef GRAPH_H
#define GRAPH_H

#include "Object.h"
#include "SharedPointer.h"
#include "DynamicArray.h"
#include "LinkQueue.h"
#include "LinkStack.h"
#include "Sort.h"

namespace DTLib
{

template <typename E>
struct Edge : public Object
{
    int b;
    int e;
    E data;

    Edge(int i=-1, int j=-1)  : b(i), e(j)
    {
    }

    Edge(int i, int j, const E &value) : b(i), e(j), data(value)
    {
    }

    bool operator == (const Edge &obj)
    {
        return (b == obj.b) && (e == obj.e);
    }

    bool operator != (const Edge &obj)
    {
        return !(*this == obj);
    }

    bool operator < (const Edge &obj)
    {
        return (data < obj.data);
    }

    bool operator > (const Edge &obj)
    {
        return (data > obj.data);
    }
};

template <typename V, typename E>
class Graph : public Object
{
public:
    virtual V getVertex(int i) const = 0;
    virtual bool getVertex(int i, V &value) const = 0;
    virtual bool setVertex(int i, const V &value) = 0;
    virtual SharedPointer<Array<int>> getAdjacent(int i) const = 0;
    virtual bool isAdjacent(int i, int j) const = 0;
    virtual E getEdge(int i, int j) const = 0;
    virtual bool getEdge(int i, int j, E &value) const = 0;
    virtual bool setEdge(int i, int j, const E &value) = 0;
    virtual bool removeEdge(int i, int j) = 0;
    virtual int vCount() const = 0;
    virtual int eCount() = 0;
    virtual int OD(int i) = 0;
    virtual int ID(int i) = 0;
    virtual int TD(int i)
    {
        return OD(i) + ID(i);
    }

    bool asUndirected()
    {
        bool ret = true;

        for (int i=0; i<vCount() && ret; ++i)
        {
            for (int j=0; j<vCount() && ret; ++j)
            {
                if (isAdjacent(i, j))
                {
                    ret = isAdjacent(j, i) && (getEdge(i, j) == getEdge(j, i));
                }
            }
        }

        return ret;
    }

    SharedPointer<Array<int>> BFS(int i)
    {
        DynamicArray<int> *ret = nullptr;

        if ((0 <= i) && (i < vCount()))
        {
            LinkQueue<int> q;
            LinkQueue<int> r;
            DynamicArray<bool> visited(vCount());

            for (int j=0; j<visited.length(); ++j)
            {
                visited[j] = false;
            }

            q.add(i);

            while (q.length() > 0)
            {
                int v = q.front();

                q.remove();

                if (!visited[v])
                {
                    SharedPointer<Array<int>> aj = getAdjacent(v);

                    for (int j=0; j<aj->length(); ++j)
                    {
                        q.add((*aj)[j]);
                    }

                    r.add(v);

                    visited[v] = true;
                }
            }

            ret = toArray(r);
        }
        else
        {
            THROW_EXCEPTION(InvalidParameterExcetion, "Parameter i is invalid ...");
        }

        return ret;
    }

#ifdef DFS_R
    SharedPointer<Array<int>> DFS(int i)  // 遞歸版深度優先遍歷
    {
        DynamicArray<int> *ret = nullptr;

        if ((0 <= i) && (i < vCount()))
        {
            LinkQueue<int> r;
            DynamicArray<bool> visited(vCount());

            for (int j=0; j<vCount(); ++j)
            {
                visited[j] = false;
            }

            DFP(i, visited, r);

            ret = toArray(r);
        }
        else
        {
            THROW_EXCEPTION(InvalidParameterExcetion, "Parameter i is invalid ...");
        }

        return ret;
    }
#else
    SharedPointer<Array<int>> DFS(int i)
    {
        DynamicArray<int> *ret = nullptr;

        if ((0 <= i) && (i < vCount()))
        {
            LinkStack<int> s;
            LinkQueue<int> r;
            DynamicArray<bool> visited(vCount());

            for (int j=0; j<visited.length(); ++j)
            {
                visited[j] = false;
            }

            s.push(i);

            while (s.size() > 0)
            {
                int v = s.top();

                s.pop();

                if (!visited[v])
                {
                    SharedPointer<Array<int>> aj = getAdjacent(v);

                    for (int j=aj->length()-1; j>=0; --j)
                    {
                        s.push((*aj)[j]);
                    }

                    r.add(v);

                    visited[v] = true;
                }
            }

            ret = toArray(r);
        }
        else
        {
            THROW_EXCEPTION(InvalidParameterExcetion, "Parameter i is invalid ...");
        }

        return ret;
    } 

#endif

    SharedPointer<Array<Edge<E>>> prim(const E &LIMIT, const bool MINIMUM = true)
    {
        LinkQueue<Edge<E>> ret;

        if (asUndirected())
        {
            DynamicArray<int> adjVex(vCount());
            DynamicArray<bool> mark(vCount());
            DynamicArray<E> cost(vCount());
            SharedPointer<Array<int>> aj = nullptr;
            bool end = false;
            int v = 0;

            for (int i=0; i<vCount(); ++i)
            {
                adjVex[i] = -1;
                mark[i] = false;
                cost[i] = LIMIT;
            }

            mark[v] = true;

            aj = getAdjacent(v);

            for (int i=0; i<aj->length(); ++i)
            {
                cost[(*aj)[i]] = getEdge(v, (*aj)[i]);
                adjVex[(*aj)[i]] = v;
            }

            for (int i=0; i<vCount() && !end; ++i)
            {
                E m = LIMIT;
                int k = -1;

                for (int j=0; j<vCount(); ++j)
                {
                    if (!mark[j] && (MINIMUM ? (m > cost[j]) : (m < cost[j])))
                    {
                        m = cost[j];
                        k = j;
                    }
                }

                end = (k == -1);

                if (!end)
                {
                    ret.add(Edge<E>(adjVex[k],k, getEdge(adjVex[k],k)));

                    mark[k] = true;

                    aj = getAdjacent(k);

                    for (int j=0; j<aj->length(); ++j)
                    {
                        if (!mark[(*aj)[j]] && (MINIMUM ? (getEdge(k, (*aj)[j]) < cost[(*aj)[j]]) : (getEdge(k, (*aj)[j]) > cost[(*aj)[j]])))
                        {
                            cost[(*aj)[j]] = getEdge(k, (*aj)[j]);

                            adjVex[(*aj)[j]] = k;
                        }
                    }
                }
            }
        }
        else
        {
            THROW_EXCEPTION(InvalidOpertionExcetion, "Prim operator is for undirected grap only ...");
        }

        if (ret.length() != (vCount() - 1))
        {
            THROW_EXCEPTION(InvalidOpertionExcetion, "No enough edge for prim operation ...");
        }

        return toArray(ret);
    }

    SharedPointer<Array<Edge<E>>> Kruskal( const bool MINIMUM = true)
    {
        LinkQueue<Edge<E>> ret;
        DynamicArray<int> p(vCount());
        SharedPointer<Array<Edge<E>>> edges = getUndirectedEdges();

        for (int i=0; i<p.length(); ++i)
        {
            p[i] = -1;
        }

        Sort::Shell(*edges, MINIMUM);

        for (int i=0; (i<edges->length()) && (ret.length() < (vCount()-1)); ++i)
        {
            int b = find(p, (*edges)[i].b);
            int e = find(p, (*edges)[i].e);

            if (b != e)
            {
                p[e] = b;

                ret.add((*edges)[i]);
            }
        }

        if (ret.length() != vCount() - 1)
        {
            THROW_EXCEPTION(InvalidOpertionExcetion, "No enough edges for Kruskal operation ...");
        }

        return toArray(ret);
    }

protected:
    template <typename T>
    DynamicArray<T>* toArray(LinkQueue<T> &queue)
    {
        DynamicArray<T> *ret = new DynamicArray<T>(queue.length());

        if (ret != nullptr)
        {
            for (int i=0; i<ret->length(); ++i, queue.remove())
            {
                ret->set(i, queue.front());
            }
        }
        else
        {
            THROW_EXCEPTION(NoEnoughMemoryException, "No memory to create ret obj ...");
        }

        return ret;
    }

#ifdef DFS_R
    void DFP(int i, DynamicArray<bool> &visited, LinkQueue<int>& queue)
    {
        if (!visited[i])
        {
            queue.add(i);

            visited[i] = true;

            SharedPointer<Array<int>> aj = getAdjacent(i);

            for (int j=0; j<aj->length(); ++j)
            {
                DFP((*aj)[j], visited, queue);
            }
        }
    }
#endif

    int find(Array<int> &p, int v)
    {
        while (p[v] != -1)
        {
            v = p[v];
        }

        return v;
    }

    SharedPointer<Array<Edge<E>>> getUndirectedEdges()
    {
        DynamicArray<Edge<E>> *ret = nullptr;

        if (asUndirected())
        {
            LinkQueue<Edge<E>> queue;

            for (int i=0; i<vCount(); ++i)
            {
                for (int j=0; j<vCount(); ++j)
                {
                    if (isAdjacent(i, j))
                    {
                        queue.add(Edge<E>(i, j, getEdge(i, j)));
                    }
                }
            }

            ret = toArray(queue);
        }
        else
        {
            THROW_EXCEPTION(InvalidOpertionExcetion, "This function is for undirected graph only ...");
        }

        return ret;
    }
};

}

#endif // GRAPH_H

文件:main.cpp數組

#include <iostream>
#include "MatrixGraph.h"
#include "ListGraph.h"

using namespace std;
using namespace DTLib;

template< typename V, typename E >
Graph<V, E>& GraphEasy()
{
    static MatrixGraph<4, V, E> g;

    g.setEdge(0, 1, 1);
    g.setEdge(1, 0, 1);

    g.setEdge(0, 2, 3);
    g.setEdge(2, 0, 3);

    g.setEdge(1, 2, 1);
    g.setEdge(2, 1, 1);

    g.setEdge(1, 3, 4);
    g.setEdge(3, 1, 4);

    g.setEdge(2, 3, 1);
    g.setEdge(3, 2, 1);

    return g;
}

template< typename V, typename E >
Graph<V, E>& GraphComplex()
{
    static ListGraph<V, E> g(9);

    g.setEdge(0, 1, 10);
    g.setEdge(1, 0, 10);

    g.setEdge(0, 5, 11);
    g.setEdge(5, 0, 11);

    g.setEdge(1, 2, 18);
    g.setEdge(2, 1, 18);

    g.setEdge(1, 8, 12);
    g.setEdge(8, 1, 12);

    g.setEdge(1, 6, 16);
    g.setEdge(6, 1, 16);

    g.setEdge(2, 3, 22);
    g.setEdge(3, 2, 22);

    g.setEdge(2, 8, 8);
    g.setEdge(8, 2, 8);

    g.setEdge(3, 8, 21);
    g.setEdge(8, 3, 21);

    g.setEdge(3, 6, 24);
    g.setEdge(6, 3, 24);

    g.setEdge(3, 7, 16);
    g.setEdge(7, 3, 16);

    g.setEdge(3, 4, 20);
    g.setEdge(4, 3, 20);

    g.setEdge(4, 5, 26);
    g.setEdge(5, 4, 26);

    g.setEdge(4, 7, 7);
    g.setEdge(7, 4, 7);

    g.setEdge(5, 6, 17);
    g.setEdge(6, 5, 17);

    g.setEdge(6, 7, 19);
    g.setEdge(7, 6, 19);

    return g;
}

void func1()
{
    cout << "func1: ---------------------" << endl;

    Graph<int, int>& g = GraphEasy<int, int>();

    SharedPointer< Array< Edge<int> > > sa = g.Kruskal();

    int w = 0;

    for(int i=0; i<sa->length(); i++)
    {
        w += (*sa)[i].data;

        cout << (*sa)[i].b << " " << (*sa)[i].e << " " << (*sa)[i].data << endl;
    }

    cout << "Weight: " << w << endl;
}

void func2()
{
    cout << "func2: ---------------------" << endl;

    Graph<int, int>& g = GraphComplex<int, int>();

    SharedPointer< Array< Edge<int> > > sa = g.Kruskal();

    int w = 0;

    for(int i=0; i<sa->length(); i++)
    {
        w += (*sa)[i].data;

        cout << (*sa)[i].b << " " << (*sa)[i].e << " " << (*sa)[i].data << endl;
    }

    cout << "Weight: " << w << endl;
}

void func3()
{
    cout << "func3: ---------------------" << endl;

    Graph<int, int>& g = GraphComplex<int, int>();

    SharedPointer< Array< Edge<int> > > sa = g.Kruskal(false);

    int w = 0;

    for(int i=0; i<sa->length(); i++)
    {
        w += (*sa)[i].data;

        cout << (*sa)[i].b << " " << (*sa)[i].e << " " << (*sa)[i].data << endl;
    }

    cout << "Weight: " << w << endl;
}

int main()
{
    func1();

    func2();

    func3();

    return 0;
}

輸出:函數

func1: ---------------------
0 1 1
1 2 1
2 3 1
Weight: 3
func2: ---------------------
4 7 7
2 8 8
1 0 10
0 5 11
1 8 12
1 6 16
3 7 16
7 6 19
Weight: 99
func3: ---------------------
5 4 26
3 6 24
2 3 22
3 8 21
3 4 20
7 6 19
1 2 18
0 5 11
Weight: 161

小結

  • Prim 算法以頂點爲核心尋找最小生成樹,不夠直接
  • Kruskal 算法以邊爲核心尋找最小生成樹,直觀簡單
  • Kruskal 算法中的關鍵是前驅標記數組的使用
  • 前驅標記數組用於判斷新選擇的邊是否會形成迴路

以上內容整理於狄泰軟件學院系列課程,請你們保護原創!this

相關文章
相關標籤/搜索