http://poj.org/problem?id=3255
写了还算多的最短路题目发现,没写过次短路。顺着挑战刷,就看到了次短路,然后发现一脸懵逼。
其实理解了后发现超级简单。次短路,每个点都记录两个距离就好了,最短的和次短的。然后最后输出第n个点的次短的即可。
代码如下:
#include<iostream>
#include<vector>
#include<utility>
#include<queue>
#include<cstdio>
using namespace std;
const int INF = 0x3f3f3f3f;
const int maxn = 5005;
typedef pair<int, int> pii;
int dis[maxn], dis_2[maxn];
struct node{
int p, val;
node(){}
node(int a, int b){
p = a;
val = b;
}
};
vector <node> edge[maxn];
inline void add_edge(int u, int v, int val){
edge[u].push_back(node(v, val));
edge[v].push_back(node(u, val));
}
void dijkstra(int s){
fill(dis, dis + maxn, INF);
fill(dis_2, dis_2 + maxn, INF);
priority_queue<pii, vector<pii>, greater<pii> >q;
q.push(make_pair(0, s));
dis[s] = 0;
while(!q.empty()){
pii now = q.top();
q.pop();
if(now.first > dis_2[now.second])
continue;
for(int i = 0; i < edge[now.second].size(); i++){
node next = edge[now.second][i];
int d = now.first + next.val;
if(dis[next.p] > d) {
swap(dis[next.p], d);
q.push(make_pair(dis[next.p], next.p));
}
if(dis[next.p] < d && dis_2[next.p] > d) {
dis_2[next.p] = d;
q.push(make_pair(d, next.p));
}
}
}
}
int main(){
int n, r, u, v, val;
cin >> n >> r;
while(r--){
scanf("%d%d%d", &u, &v, &val);
add_edge(u, v, val);
}
dijkstra(1);
cout << dis_2[n] << endl;
return 0;
}