POJ No.3255 Roadblocks 求次短路径

 1 #define _CRT_SECURE_NO_WARNINGS
 2 /*
 3 7 10
 4 0 1 5
 5 0 2 2
 6 1 2 4
 7 1 3 2
 8 2 3 6
 9 2 4 10
10 3 5 1
11 4 5 3
12 4 6 5
13 5 6 9
14 
15 4 4
16 0 1 100
17 1 3 200
18 1 2 250
19 2 3 100
20 */
21 #include <iostream>
22 #include <functional>
23 #include <utility>
24 #include <queue>
25 #include <vector>
26 using namespace std;
27 
28 const int maxn = 1010 + 20;
29 const int INF = 9999999;
30 typedef pair<int, int> P;     //first-最短距离,second-顶点编号
31 struct edge
32 {
33     int to, cost;
34 };
35 
36 //输入
37 int N, R;             //N-点,R-边  
38 vector<edge> G[maxn]; //图的邻接表表示
39 
40 int dist[maxn];   //最短距离
41 int dist2[maxn];  //次短距离
42 
43 void solve()
44 {
45     priority_queue<P, vector<P>, greater<P> > que;
46     fill(dist, dist + N, INF);
47     fill(dist2, dist2 + N, INF);
48     dist[0] = 0;
49     que.push(P(0, 0));
50 
51     while (!que.empty())
52     {
53         P p = que.top(); que.pop();       //队列存放 (最短路和次短路)
54         int v = p.second, d = p.first;
55         if (dist2[v] < d) continue;       //如果次小的值小,跳过该值
56         for (int i = 0; i < G[v].size(); i++) {
57             edge &e = G[v][i];            //得到v的临边
58             int d2 = d + e.cost;          //d2 = 已知最短或次短 + 临边权值
59             if (dist[e.to] > d2) {        //如果未确定的最短路 > d2
60                 swap(dist[e.to], d2);     
61                 que.push(P(dist[e.to], e.to));   //添加最短路
62             }
63             if (dist2[e.to] > d2 && dist[e.to] < d2) {
64                 dist2[e.to] = d2;                //说明d2是次大值
65                 que.push(P(dist2[e.to], e.to));  //添加次短路
66             }
67         }
68     }
69     printf("%d
", dist2[N - 1]);        //N位置的dist2即为
70 }
71 
72 void input()
73 {
74     int from, to, cost;
75     edge tmp;
76     for (int i = 0; i < R; i++) {
77         cin >> from >> to >> cost;
78         tmp.to = to; tmp.cost = cost;
79         G[from].push_back(tmp);
80         tmp.to = from;
81         G[to].push_back(tmp);
82     }
83 }
84 
85 int main()
86 {
87     cin >> N >> R;
88     input();
89     solve();
90     return 0;
91 }
原文地址:https://www.cnblogs.com/douzujun/p/6420766.html