poj3255

本文地址:https://www.cnblogs.com/maplefighting/p/9124073.html

题目名称:Roadblocks

链接:http://poj.org/problem?id=3255

题意:有 N 个点,R条边,计算从 1 出发到 N的次短路长度,次短路是指长度比那些最短路长的路径。

思路:emmm,最短路是每次保存最短的点,那我们每次保存最短和次短就好了

代码如下:

 

 1 #include<cstdio>
 2 #include<iostream>
 3 #include<queue>
 4 using namespace std;
 5 typedef pair<int,int> P;
 6 const int INF = 0x3f3f3f3f;
 7 const int maxn = 5005;
 8 struct Edge{
 9     int v, w;
10     int nxt;
11 }edge[100005 * 2];
12 int head[maxn];
13 int n, r;
14 int cnt, dist1[maxn], dist2[maxn];
15 void add_edge(int u, int v, int w){
16     edge[cnt].v = v;
17     edge[cnt].w = w;
18     edge[cnt].nxt = head[u];
19     head[u] = cnt++;
20 }
21 void init(){
22     cnt = 0;
23     fill(head, head + n + 1, -1);
24     fill(dist1, dist1 + n + 1, INF);
25     fill(dist2, dist2 + n + 1, INF);
26 }
27 void spfa(int s){
28     priority_queue<P, vector<P>, greater<P> > Q;
29     dist1[s] = 0;
30     Q.push(P(0, 1));
31     while(!Q.empty()){
32         P p = Q.top(); Q.pop();
33         int v = p.second, w = p.first;
34         if(dist2[v] < w) continue;
35         for(int i = head[v]; i != -1; i = edge[i].nxt){
36             Edge &e = edge[i];
37             int d = w + e.w;
38             if(dist1[e.v] > d){
39                 swap(dist1[e.v], d);
40                 Q.push(P(dist1[e.v], e.v));
41             }
42             if(dist2[e.v] > d && dist1[e.v] < d){
43                 dist2[e.v] = d;
44                 Q.push(P(dist2[e.v], e.v));
45             }
46         }
47     }
48 }
49 int main(){
50 
51     scanf("%d%d", &n, &r);
52     init();
53     for(int i = 1; i <= r; i++){
54         int a,b,d;
55         scanf("%d%d%d", &a, &b, &d);
56         add_edge(a, b, d);
57         add_edge(b, a, d);
58     }
59     spfa(1);
60     printf("%d\n", dist2[n]);
61     return 0;
62 }
View Code

 

posted @ 2018-06-01 23:36  maplefighting  阅读(139)  评论(0编辑  收藏  举报