求次短路,模板题
//2788K 219MS
#include <cstdio>
#include <iostream>
#include <cstring>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;
typedef pair<int, int> pii;
const int maxn = 5000;
const int maxm = 100000;
const int inf = 0x7fffffff;
vector<pii> G[maxn+5];
int d1[maxn+5], d2[maxn+5];
int n, m;
void Dijkstra(int s){
fill(d1+1, d1+n+1, inf);
fill(d2+1, d2+n+1, inf);
d1[s] = 0; //s到s的次短路径不能初始化为0
priority_queue< pii, vector<pii>, greater<pii> > pque;
pque.push(pii(0, s));
while(!pque.empty()){
pii f = pque.top(); pque.pop();
if(f.first > d2[f.second]) continue;
int len = G[f.second].size();
for(int i=0; i<len; i++){
pii e = G[f.second][i];
int dd = f.first + e.first;
if(dd < d1[e.second]){
swap(dd, d1[e.second]);
pque.push(pii(d1[e.second], e.second));
}
if(dd < d2[e.second]){
d2[e.second] = dd;
pque.push(pii(d2[e.second], e.second));
}
}
}
}
int main(){
while(~scanf("%d%d", &n, &m)){
for(int i=1; i<=m; i++){
int a, b, d;
scanf("%d%d%d", &a, &b, &d);
G[a].push_back(pii(d, b));
G[b].push_back(pii(d, a));
}
Dijkstra(1);
printf("%d\n", d2[n]);
for(int i=1; i<=n; i++)
G[i].clear();
}
return 0;
}