Not the Best
Description
Robin has moved to a small village and sometimes enjoys returning to visit one of his best friends. He does not want to get to his old home too quickly, because he likes the scenery along the way. He has decided to take the second-shortest rather than the shortest path. He knows there must be some second-shortest path.
The countryside consists of R bidirectional roads, each linking two of the N intersections, conveniently numbered from 1 to N. Robin starts at intersection 1, and his friend (the destination) is at intersection N.
The second-shortest path may share roads with any of the shortest paths, and it may backtrack i.e., use the same road or intersection more than once. The second-shortest path is the shortest path whose length is longer than the shortest path(s) (i.e., if two or more shortest paths exist, the second-shortest path is the one whose length is longer than those but no longer than any other path).
Input
Input starts with an integer T (≤ 10), denoting the number of test cases.
Each case contains two integers N (1 ≤ N ≤ 5000) and R (1 ≤ R ≤ 105). Each of the next R lines contains three space-separated integers: u, v and wthat describe a road that connects intersections u and v and has length w (1 ≤ w ≤ 5000).
Output
For each case, print the case number and the second best shortest path as described above.
Sample Input
2
3 3
1 2 100
2 3 200
1 3 50
4 4
1 2 100
2 4 200
2 3 250
3 4 100
Sample Output
Case 1: 150
Case 2: 450
解题思路:
次短路。。。
AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#define INF 0xfffffff
using namespace std;
struct Edge{
int to,cost;
};
int n,r;
vector<Edge> edge[5005];
typedef pair<int,int> P;//first是最短距离,second是顶点编号
int dis1[5005];//最短距离
int dis2[5005];//次短距离
int solve(){
priority_queue<P,vector<P>,greater<P> > q;
for(int i = 0; i <= n; i++){
dis1[i] = INF;
dis2[i] = INF;
}
dis1[1] = 0;
q.push(P(0,1));
while(!q.empty()){
P p = q.top();
q.pop();
int v = p.second,d = p.first;
if(dis2[v] < d)
continue;
for(int i = 0; i < edge[v].size(); i++){
Edge &e = edge[v][i];
int d2 = d + e.cost;
if(dis1[e.to] > d2){
swap(dis1[e.to],d2);
q.push(P(dis1[e.to],e.to));
}
if(dis2[e.to] > d2 && dis1[e.to] < d2){
dis2[e.to] = d2;
q.push(P(dis2[e.to],e.to));
}
}
}
return dis2[n];
}
int main(){
int T,t = 1;
scanf("%d",&T);
while(T--){
scanf("%d%d",&n,&r);
for(int i = 0; i <= n; i++)
edge[i].clear();
int u,v,cost;
Edge tmp;
for(int i = 0; i < r; i++){
scanf("%d%d%d",&u,&v,&cost);
tmp.to = v;tmp.cost = cost;
edge[u].push_back(tmp);
tmp.to = u;
edge[v].push_back(tmp);
}
solve();
printf("Case %d: %d\n",t++,solve());
}
return 0;
}