MST

Posted 十木禾

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MST相关的知识,希望对你有一定的参考价值。

以下介绍使用Kruskal算法实现最小生成树

定义边的类

class Line 
public:
    int n1, n2; // 边连接到点
    int cost;   // 花费

    Line() = default;
    Line(int n1, int n2, int cost): n1(n1), n2(n2), cost(cost) 

    bool operator> (Line L) const 
        return cost > L.cost;
    

    void print() const  cout<<n1<<"<---->"<<n2<<endl; 
;

定义并查集的类

class UnionSet 
public:
    const int DEFAULT_STATE = 0;
    int* Tag;
    int size;
    int state = DEFAULT_STATE;

    UnionSet() = default;
    UnionSet(int size): size(size) 
        Tag = new int [size];
    

    bool cycle(int n1, int n2) 
        return Tag[n1] == Tag[n2] && Tag[n1] != DEFAULT_STATE;
    
    bool insert(int n1, int n2) 
        if (cycle(n1, n2)) return false;
        int t1 = Tag[n1], t2 = Tag[n2];

        if (t1 == t2 && t1 == DEFAULT_STATE) Tag[n1] = Tag[n2] = ++ state;
        else if (t1 == DEFAULT_STATE) Tag[n1] = t2;
        else if (t2 == DEFAULT_STATE) Tag[n2] = t1;
        else 
            for(int i=1; i<=size; i++)
                if (Tag[i] == t2) Tag[i] = t1;
            
        

        return true;
    
;

定义图的类

class Graph 
private:
    bool select(Line L) 
        return unionSet->insert(L.n1, L.n2);
    
public:
    priority_queue<Line, vector<Line>, greater<Line>> lineList;
    UnionSet* unionSet;

    Graph() = default;
    Graph(int size)  unionSet = new UnionSet(size); 

    void insertLine(int n1, int n2, int cost) 
        lineList.push(Line(n1, n2, cost));
    

    int mstCost() 
        int minCost = 0;

        Line minLine;

        while (!lineList.empty()) 
            do 
                minLine = lineList.top();
                lineList.pop();
                if (lineList.empty()) return minCost;
             while (!select(minLine));

            minCost += minLine.cost;
            minLine.print();
        

        return minCost;
    
;

以上是关于MST的主要内容,如果未能解决你的问题,请参考以下文章

POJ-1679 The Unique MST (判断最小生成树的唯一性)

POJ-1679 The Unique MST---判断最小生成树是否唯一

POJ1679(判断是否为唯一MST)

CF888G Xor-MST 异或MST

D. GCD and MST(MST&双指针)

poj 1679 The Unique MST (次小生成树(sec_mst)kruskal)