Roadblocks
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
该题是要求1-n的次短路,那么我们首先要知道1-n的最短路是多少,然后再从1-n的其他路径中取最短的且比1-n的最短路长的路
我们可以认为次短路是,大部分和最短路径一样,只是其中某一段(未必仅是一条边)不一样,那么我们可以求dis1[i]数组表示1-i的最短路,dis2[i]数组表示n-i的最短路
那么dis1【n】=dis1[i]+e[i][j]+dis2[j]
所以我们可以枚举一下i和j (j>i)与最短路进行比较即可得知
代码如下:
#include<stdio.h>
#include<queue>
#include<string.h>
#include<algorithm>
#define inf 0x3f3f3f3f
using namespace std;
const int maxn=100010;
int book[5500],dis1[5500],dis2[5500],w[5500],k=0,m,n;
int a[2*maxn],b[2*maxn],c[2*maxn];
struct node
{
int x,money,next;
}s[maxn*2];
void add(int a,int b,int c)
{
s[k].x=b,s[k].money=c;s[k].next=w[a];
w[a]=k++;
}
void SPFA(int x, int *dis)
{
queue<int>q;
q.push(x);
for(int i=0;i<=n;i++)
dis[i]=inf;
dis[x]=0;
while(!q.empty())
{
x=q.front();
q.pop();
book[x]=0;
for(int i=w[x];i!=-1;i=s[i].next)
{
int y=s[i].x;
if(dis[y]>dis[x]+s[i].money)
{
dis[y]=dis[x]+s[i].money;
if(book[y]==0)
{
book[y]=1;
q.push(y);
}
}
}
}
}
int main()
{
scanf("%d%d",&n,&m);
memset(w,-1,sizeof(w));
for(int i=0;i<2*m;i+=2)
{
scanf("%d%d%d",&a[i],&b[i],&c[i]);
a[i+1]=b[i];b[i+1]=a[i];c[i+1]=c[i];
add(a[i],b[i],c[i]);
add(a[i+1],b[i+1],c[i+1]);
}
SPFA(1,dis1);
SPFA(n,dis2);
int min2=inf;
for(int i=0;i<2*m;i++)
{
int minn=dis1[a[i]]+dis2[b[i]]+c[i];
if(minn>dis1[n])
min2=min(min2,minn);
}
printf("%d\n",min2);
}