标签:while for priority 内容 size res class als max
交通规划
解题思路:
在dijkstra求单源点路径最短的情况下实现最小花费
代码如下:
1 #include <iostream> 2 #include <queue> 3 #include <vector> 4 5 #define NMAX 10005 6 #define INTMAX 0x7fffffff 7 8 using namespace std; 9 10 // v表示节点,cost表示出发点到v点的距离 11 struct Node { 12 int v; 13 int cost; 14 Node(int vv = 0, int c = 0) { 15 v = vv, cost = c; 16 } 17 // 优先队列将按距离从小到大排列 18 friend bool operator<(Node n1, Node n2) { 19 return n1.cost > n2.cost; 20 } 21 }; 22 23 // v表示边的另一端节点,cost表示该边的权重 24 struct Edge { 25 int v; 26 int cost; 27 Edge(int vv = 0, int c = 0) { 28 v = vv, cost = c; 29 } 30 }; 31 32 vector<Edge>G[NMAX]; // 无向图 33 bool marked[NMAX]; // D算法中每个顶点仅处理一遍 34 int disto[NMAX]; // 出发点到某点距离 35 int costo[NMAX]; // 接通该点需要增加的边的权重 36 int N, M; 37 38 void dijkstra(int s) { 39 for (int i = 0; i <= N; i++) { 40 costo[i] = disto[i] = INTMAX;//初始化 41 marked[i] = false; 42 } 43 disto[s] = 0; 44 costo[s] = 0; 45 priority_queue<Node>pq; // 保存<v,disto[v]>且按disto[v]升序排列 46 pq.push(Node(s, 0)); 47 marked[0]=true; 48 49 Node tmp; 50 while (!pq.empty()) { 51 tmp = pq.top(); 52 pq.pop(); 53 int v = tmp.v; 54 if (!marked[v]) { 55 marked[v]=true; 56 int len = G[v].size(); 57 for (int i = 0; i < len; i++) { 58 int vv = G[v][i].v; 59 if(marked[vv]) 60 continue; 61 int cost = G[v][i].cost; 62 int newdist = disto[v] + cost; 63 if (disto[vv] > newdist) { 64 disto[vv] = newdist; 65 costo[vv] = cost; // 增加的内容 66 pq.push(Node(vv, disto[vv])); 67 } 68 // 加入点vv时若出现多种距离相同的方案,选取新边最小那个 69 if (disto[vv] == newdist) { 70 costo[vv] = min(costo[vv], cost); 71 } 72 } 73 } 74 } 75 } 76 77 int main(void) { 78 cin >> N >> M; 79 80 int s, e, c; 81 for (int i = 0; i < M; i++) { 82 cin >> s >> e >> c; 83 G[s].push_back(Edge(e, c));//无线图中添加边 84 G[e].push_back(Edge(s, c)); 85 } 86 dijkstra(1); 87 88 // 统计边权重 89 int res = 0; 90 for (int i = 2; i <= N; i++) { 91 res += costo[i]; 92 } 93 cout << res << endl; 94 95 return 0; 96 }
ps:相关资料来自于网上
标签:while for priority 内容 size res class als max
原文地址:http://www.cnblogs.com/qiujun/p/6183980.html