原题链接
Problem Description
Bessie has moved to a small farm and sometimes enjoys returning to visit one of her best friends. She does not want to get to her old home too quickly, because she likes the scenery along the way. She has decided to take the second-shortest rather than the shortest path. She knows there must be some second-shortest path.
The countryside consists of R (1 ≤ R ≤ 100,000) bidirectional roads, each linking two of the N (1 ≤ N ≤ 5000) intersections, conveniently numbered 1..N. Bessie starts at intersection 1, and her friend (the destination) is at intersection N.
The second-shortest path may share roads with any of the shortest paths, and it may backtrack i.e., use the same road or intersection more than once. The second-shortest path is the shortest path whose length is longer than the shortest path(s) (i.e., if two or more shortest paths exist, the second-shortest path is the one whose length is longer than those but no longer than any other path).
Input
Line 1: Two space-separated integers: N and R
Lines 2..R+1: Each line contains three space-separated integers: A, B, and D that describe a road that connects intersections A and B and has length D (1 ≤ D ≤ 5000)
Output
Line 1: The length of the second shortest path between node 1 and node N
Sample Input
4 4
1 2 100
2 4 200
2 3 250
3 4 100
Sample Output
450
题目大意
次短路裸题
解题思路
在求最短路的Dijkstra过程中,另外再设一个次短路数组,每次维护最短路的时候,连着次短路一起维护就好。
AC代码
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<string>
#include<queue>
#include<list>
#include<stack>
#include<set>
#include<map>
#define ll long long
#define ull unsigned long long
#define rep(i,a,b) for (int i=(a),_ed=(b);i<=_ed;i++)
#define rrep(i,a,b) for(int i=(a),_ed=(b);i>=_ed;i--)
#define fil(a,b) memset((a),(b),sizeof(a))
#define cl(a) fil(a,0)
#define PI 3.1415927
#define inf 0x3f3f3f3f
#define P pair<int,int>
#define mp(a,b) make_pair<a,b>
#define pb push_back
using namespace std;
int n, r,from,to,cost;
struct edge
{
int to;
int cost;
};
edge temp;
int main(void)
{
while (scanf("%d%d", &n, &r) != EOF)
{
vector<edge> E[5005];
priority_queue<P, vector<P>, greater<P> > pq;
int d[5005];
int dd[5005];
fil(d, inf);
fil(dd, inf);
d[1] = 0;
rep(i, 1, r)
{
scanf("%d%d%d", &from, &to,&cost);
temp.cost = cost;
temp.to = to;
E[from].pb(temp);
temp.to = from;
E[to].pb(temp);
}
pq.push(P(0, 1));
while (!pq.empty())
{
P buff = pq.top();
pq.pop();
int v = buff.second;
if (buff.first > dd[v]) continue;
for (int i = 0;i < E[v].size();++i)
{
edge e = E[v][i];
if (buff.first + e.cost < d[e.to])
{
dd[e.to] = d[e.to];
d[e.to] = buff.first + e.cost;
pq.push(P(d[e.to], e.to));
pq.push(P(dd[e.to], e.to));
}
else if (buff.first + e.cost > d[e.to] && buff.first + e.cost < dd[e.to])
{
dd[e.to] = buff.first + e.cost;
pq.push(P(dd[e.to], e.to));
}
}
}
printf("%d\n", dd[n]);
}
return 0;
}