标签:
给定N个点,以及每两个点之间的路径长度,求出一个连接这N个点的方案,使得连接这N个点的总长度最短,求出该总长度。
求最小生成树MST的模板题,直接使用prim算法进行求解。
#include<stdio.h> #include<vector> #include<queue> #include<string.h> #include<algorithm> using namespace std; #define MAX_NODE 105 struct Edge{ int vertex; int dist; Edge(int v, int d) : vertex(v), dist(d){}; }; vector<vector<Edge> > gGraph; struct Compare{ bool operator()(const Edge& e1, const Edge& e2){ return e1.dist > e2.dist; } }; bool gVisited[MAX_NODE]; int Prim(int n){ //prim算法加堆优化 memset(gVisited, false, sizeof(gVisited)); //随便选择一个起点,假设从0开始 Edge e(0, 0); int sum_mst = 0; priority_queue<Edge, vector<Edge>, Compare> pq; pq.push(e); while (!pq.empty()){ e = pq.top(); pq.pop(); if (gVisited[e.vertex]) continue; gVisited[e.vertex] = true; sum_mst += e.dist; for (int i = 0; i < gGraph[e.vertex].size(); i++){ //将该点连接边都加入到优先队列中,进行下一轮选择 pq.push(gGraph[e.vertex][i]); } } return sum_mst; } int main(){ int n, dist; while (scanf("%d", &n) != EOF){ gGraph.clear(); gGraph.resize(n); for (int i = 0; i < n; i++){ for (int j = 0; j < n; j++){ scanf("%d", &dist); gGraph[i].push_back(Edge(j, dist)); } } int result = Prim(n); printf("%d\n", result); } return 0; }
标签:
原文地址:http://www.cnblogs.com/gtarcoder/p/4867362.html