浙大陈越数据结构-08-图7 公路村村通

从一个点开始向外扩展使用prim算法。
根据题意是稠密图,使用邻接矩阵区域存储整个图。
不需要存储最小生成树的图,只需要统计出所用的花费即可。
使用最小堆去选择下一条边 【优先队列】
从一个点开始,将它的所有边放到最小堆中。
在最小堆中选择最小的边,判断终点是否在图中,不在的话就将终点收进来并将终点的所有与外界相连的边收进来。重复这一步
一直到收进来的点等于所有点个个数或者最小堆已空。
如果收进来的点个数小于所有点的个数,说明图不是连通的,返回-1.
不然返回最低成本.

#include 
#include 
#include 

using namespace std;
typedef pair PAIR;//first为coast,second为终点

struct Graph{
    int m_nodeNum;
    vector> m_graph;
    Graph(int node);
    void insert(int village1, int village2, int coast);
};
Graph::Graph(int nodeNum) : m_nodeNum(nodeNum), m_graph(vector>(nodeNum + 1, vector(nodeNum + 1, -1))){
    for(int i = 1; i <= m_nodeNum; i++){
        m_graph[i][i] = 0;
    }
}
void Graph::insert(int village1, int village2, int coast) {
    m_graph[village1][village2] = m_graph[village2][village1] = coast;
}

int prim(Graph& graph){
    priority_queue, greater> minHeap;
    int startNode = 1;
    int nodeNum = graph.m_nodeNum;
    vector visited(nodeNum, false);
    visited[startNode] = true;
    int visitedNodeNum = 1;
    int sumCoast = 0;
    for(int i = 1; i <= nodeNum; i++){
        if(graph.m_graph[startNode][i] != -1 && i != startNode){
            minHeap.push({graph.m_graph[startNode][i], i});
        }
    }
    while(!minHeap.empty() && visitedNodeNum < nodeNum){
        PAIR curEdge = minHeap.top();
        minHeap.pop();
        if(visited[curEdge.second])
            continue;
        visited[curEdge.second] = true;
        sumCoast += curEdge.first;
        visitedNodeNum++;
        for(int i = 1; i <= nodeNum; i++){
            if(i != curEdge.second && graph.m_graph[curEdge.second][i] != -1 && !visited[i]){
                minHeap.push({graph.m_graph[curEdge.second][i], i});
            }
        }
    }
    if(visitedNodeNum < nodeNum)
        return -1;
    return sumCoast;
}

int main(){
    int N, M;
    cin >> N >> M;
    Graph graph(N);
    for(int i = 0; i < M; i++){
        int village1, village2, coast;
        cin >> village1 >> village2 >> coast;
        graph.insert(village1, village2, coast);
    }
    cout << prim(graph);
    return 0;
}

你可能感兴趣的:(数据结构,算法,图论)