题意:求次短路。
分析:关键是情况讨论。
LL tmpd = x.d + e.dist;
以下情况对应的更新结果
1、tmpd(2) < 最短路(3) < 次短路(4)-------> 最短路 = 2,次短路 = 3
2、tmpd(2) = 最短路(2) < 次短路(3)-------> 最短路 = 2,次短路 = 2
3、最短路(2) < tmpd(3) < 次短路(4)-------> 最短路 = 2,次短路 = 3
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<cmath>
#include<iostream>
#include<sstream>
#include<iterator>
#include<algorithm>
#include<string>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<deque>
#include<queue>
#include<list>
#define Min(a, b) ((a < b) ? a : b)
#define Max(a, b) ((a < b) ? b : a)
const double eps = 1e-8;
inline int dcmp(double a, double b){
if(fabs(a - b) < eps) return 0;
return a > b ? 1 : -1;
}
typedef long long LL;
typedef unsigned long long ULL;
const int INT_INF = 0x3f3f3f3f;
const int INT_M_INF = 0x7f7f7f7f;
const LL LL_INF = 0x3f3f3f3f3f3f3f3f;
const LL LL_M_INF = 0x7f7f7f7f7f7f7f7f;
const int dr[] = {0, 0, -1, 1, -1, -1, 1, 1};
const int dc[] = {-1, 1, 0, 0, -1, 1, -1, 1};
const int MOD = 1e9 + 7;
const double pi = acos(-1.0);
const int MAXN = 100000 + 10;
const int MAXT = 10000 + 10;
using namespace std;
struct Edge{
int from, to;
LL dist;
Edge(int f, int t, LL d):from(f), to(t), dist(d){}
};
struct HeapNode{
LL d;
int u;
HeapNode(LL dd, int uu):d(dd), u(uu){}
bool operator < (const HeapNode& rhs)const{
return d > rhs.d;
}
};
struct Dijkstra{
int n, m;
vector<Edge> edges;
vector<int> G[MAXN];
LL dist1[MAXN];
LL dist2[MAXN];
void init(int n){
this -> n = n;
for(int i = 0; i < n; ++i) G[i].clear();
edges.clear();
}
void AddEdge(int from, int to, LL dist){
edges.push_back(Edge(from, to, dist));
m = edges.size();
G[from].push_back(m - 1);
}
void dijkstra(int s){
priority_queue<HeapNode> Q;
for(int i = 0; i < n; ++i){
dist1[i] = LL_INF;
dist2[i] = LL_INF;
}
dist1[s] = 0;
Q.push(HeapNode(0, s));
while(!Q.empty()){
HeapNode x = Q.top();
Q.pop();
int u = x.u;
if(x.d > dist2[u]) continue;
for(int i = 0; i < G[u].size(); ++i) {
Edge &e = edges[G[u][i]];
LL tmpd = x.d + e.dist;
if(tmpd < dist1[e.to]){
swap(tmpd, dist1[e.to]);
Q.push(HeapNode(dist1[e.to], e.to));
}
else if(tmpd == dist1[e.to]){
dist2[e.to] = tmpd;
Q.push(HeapNode(dist2[e.to], e.to));
}
if(tmpd > dist1[e.to] && tmpd < dist2[e.to]){
dist2[e.to] = tmpd;
Q.push(HeapNode(dist2[e.to], e.to));
}
}
}
}
}dij;
int main(){
int T;
scanf("%d", &T);
while(T--){
int n, m;
scanf("%d%d", &n, &m);
dij.init(n);
int x, y;
LL d;
for(int i = 0; i < m; ++i){
scanf("%d%d%lld", &x, &y, &d);
dij.AddEdge(x - 1, y - 1, d);
dij.AddEdge(y - 1, x - 1, d);
}
dij.dijkstra(0);
printf("%lld\n", dij.dist2[n - 1]);
}
return 0;
}