zoukankan      html  css  js  c++  java
  • 算法-图论-最小生成树-Prim

    利用最小索引堆优化prim

    #include <iostream>
    #include <vector>
    #include <cassert>
    #include "Edge.h"
    #include "IndexMinHeap.h"
    
    using namespace std;
    
    template<typename Graph,typename Weight>
    class PrimMST
    {
    private:
        Graph &G;
        IndexMinHeap<Weight> ipq;
        vector<Edge<Weight>*> edgeTo;
        bool* marked;
        vector<Edge<Weight>> mst;
        Weight mstWeight;
    
        void visit(int v){
            assert(!marked[v])
            marked[v] = true;
            typename Graph::adjIterator adj(G.v);
            for(Edge<Weight>* e = adj.begin();!adj.end();e=adj.next()){
                int w = e->other(v);//相邻的顶点
                if(!marked[w]){
                    if(!edgeTo[w]){
                        ipq.insert(w,e->wt());
                        edgeTo[w]=e;
                    }else if(e->wt() < edgeTo[w]->wt()){
                        edgeTo[w]=e;
                        ipq.change(w,e->wt());
                    }
                }
            }
        }
    public:
        PrimMST(Graph &graph):G(graph),ipq(IndexMinHeap<double>(graph.V())){
            marked = new bool[G.V()];
            for(int i =0;i<G.V();i++){
                marked[i] = false;
                edgeTo.push_back(NULL);
            }
            mst.clear();
    
            //Prim
            visit(0);
            while (!ipq.isEmpty())
            {
                int v = ipq.extractMinIndex();
                assert(edgeTo[v]);
                mst.push_back(*edgeTo[v]);
                visit(v);
            };
            mstWeight = mst[0].wt();
            for(int i =1;i<mst.size();i++)
                mstWeight += mst[i].wt();
            
        };
        ~PrimMST(){
            delete[] marked;
        };
        vector<Edge<Weight>> mstEdges(){
            return mst;
        };
        Weight result(){
            return mstWeight;
        }
    
    };
  • 相关阅读:
    Redhat 7使用CentOS 7的Yum网络源
    指定YUM安装包的体系结构或版本
    CURL常用命令
    VIM技巧之去除代码行号并缩进代码
    VIM 中鼠标选择不选中行号
    linux服务器性能优化
    阻塞,非阻塞,同步,异步
    WEB三层架构与MVC
    mvc与三层结构
    Centos环境下Tomcat启动缓慢
  • 原文地址:https://www.cnblogs.com/Erick-L/p/12666258.html
Copyright © 2011-2022 走看看