题意:求次短路
思路:见注释,用dijkstra同时维护最短路和次短路
// Decline is inevitable
// Romance will last forever
// UVA 10917
#include <bits/stdc++.h>
#define mst(a, x) memset(a, x, sizeof(a))
#define INF 0x3f3f3f3f
using namespace std;
const int maxn = 5e3 + 10;
const int maxm = 2e5 + 10;
struct Edge {
int to, dis, next;
}edge[maxm];
int n, m;
int head[maxn], dis[maxn], cnt; //最短路
int dis2[maxn]; //次短路
struct node {
int dis;
int pos;
node(int _dis = 0, int _pos = 0) : dis(_dis), pos(_pos) {}
bool operator <(const node &x) const {
return dis > x.dis;
}
};
void add_edge(int u, int v, int w) {
cnt++;
edge[cnt].to = v;
edge[cnt].dis = w;
edge[cnt].next = head[u];
head[u] = cnt;
}
priority_queue<node> q;
void dijkstra(int s) {
mst(dis, 0x3f);
mst(dis2, 0x3f);
while(!q.empty()) q.pop();
dis[s] = 0;
q.push(node(0, s));
while(!q.empty()) {
node tmp = q.top();
q.pop();
int x = tmp.pos;
int p = tmp.dis;
if(dis2[x] < p) continue; //如果p比第二短路都大,那么就可以直接跳过
for(int i = head[x]; i; i = edge[i].next) {
int y = edge[i].to;
int d2 = p + edge[i].dis; //注意松弛操作不能d2 = dis[x] + edge[i].dis;
//只能用tmp.dis, 要不然就无法用次短路更新次短路
if(d2 < dis[y]) //如果这条路比最短路短 更新最短路
dis[y] = d2,
q.push(node(dis[y], y));
if(dis[y] < d2 && d2<dis2[y])
dis2[y] = d2, //若比最短路长,次短路短,则更新次短路
q.push(node(dis2[y], y)); //记得把这个次短路也加入队列
}
}
}
int main() {
cin >> n >> m;
for(int i = 1; i <= m; i++) {
int u, v, w;
cin >> u >> v >> w;
add_edge(u, v, w),
add_edge(v, u, w);
}
dijkstra(1);
cout << dis2[n] << endl;
return 0;
}