给你N个点和R条边,问从起点到终点的次短路是多少。无向边,且可重复走。
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
#define MAXN 100009
#define INF 0x3f3f3f3f
using namespace std;
typedef long long ll;
struct edge
{
int to, cost;
edge(int tv = 0, int tc = 0):
to(tv), cost(tc) {}
};
typedef pair<ll,ll> P;
int N, R;
vector<edge> graph[MAXN];
ll dist[MAXN]; //最短距离
ll dist2[MAXN]; //次短距离
void solve()
{
memset(dist, 0x3f, sizeof(dist));
memset(dist2, 0x3f, sizeof(dist2));
priority_queue<P, vector<P>, greater<P> > Q;
dist[1] = 0;
Q.push(P(0, 1));
while(!Q.empty())
{
P p = Q.top();
Q.pop();
int v = p.second;
ll d = p.first;
if(dist2[v] < d) continue;
for(unsigned i = 0; i < graph[v].size(); i++)
{
edge &e = graph[v][i];
ll d2 = d + e.cost;
if(dist[e.to] > d2)
{
swap(dist[e.to], d2);
Q.push(P(dist[e.to], e.to));
}
if(dist2[e.to] > d2 && dist[e.to] < d2)
{
dist2[e.to] = d2;
Q.push(P(dist2[e.to], e.to));
}
}
}
printf("%lld\n", dist2[N]);
}
int main()
{
int A, B, D;
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d%d", &N, &R);
for(int i=0;i<=N;i++)
graph[i].clear();
for(int i = 0; i < R; i++)
{
scanf("%d%d%d", &A, &B, &D);
graph[A].push_back(edge(B, D));
graph[B].push_back(edge(A, D));
}
solve();
}
return 0;
}
/*
Sample Input
2
3 3
1 2 1
2 3 4
1 3 3
2 1
1 2 1
Sample Output
5
3
*/