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
大意
给你 N 个点 R 条无向路让你求出从1 到 N 比最短路长的最短路,即次短路。
思路
从1到一个点的最短距离加上从这个点到另一个点的距离,再加上另一个点到N的最短距离,必定大于等于最短距离,找到其中大于最短路的最小距离,就是要找的次短路。
求出从1点到其他点的最短路,其他点到 N 点的最短路(N到其他点的最短路),然后遍历给定的每条边从 替换最短路中的边
dis[i] + dis[j] +e[i][j]
代码
#include <cstdiO>
#include <cstring>
#include <algorithm>
#define inf 0x3f3f3f3f
#define MX 200010
#define MS 5010
using namespace std;
int N,R,frt[MS],next[MX];
int g,v1[MX],v2[MX],v3[MX];
int dis1[MS],dis2[MS],v[MS];
void add(int x,int y,int z)
{
v1[g]=x,v2[g]=y,v3[g]=z;
next[g]=frt[x];
frt[x]=g;
g++;
}
void dijstr(int sr,int dis[])
{
int i,j,k,u,mi;
memset(v,0,sizeof(v));
for(i=1; i<=N; i++)
dis[i]=inf;
for(i=frt[sr]; i!=-1; i=next[i])
dis[v2[i]]=min(dis[v2[i]],v3[i]);
v[sr]=1,dis[sr]=0;
for(i=1; i<N; i++)
{
u=0,mi=inf;
for(j=1; j<=N; j++)
{
if(v[j]==0&&dis[j]<mi)
{
mi=dis[j];
u=j;
}
}
if(u==0) break;
v[u]=1;
for(k=frt[u]; k!=-1; k=next[k])
{
if(dis[v2[k]]>dis[u]+v3[k])
dis[v2[k]]=dis[u]+v3[k];
}
}
}
int main()
{
while(~scanf("%d%d",&N,&R))
{
g=0;
int i,j,t1,t2,t3,mi=inf;
memset(frt,-1,sizeof(frt));
for(i=0; i<R; i++)
{
scanf("%d%d%d",&t1,&t2,&t3);
add(t1,t2,t3);
add(t2,t1,t3);
}
dijstr(1,dis1);
dijstr(N,dis2);
for(i=0; i<g; i++)
{
int ds=dis1[v1[i]]+dis2[v2[i]]+v3[i];
if(ds>dis1[N]&&mi>ds)
mi=ds;
}
printf("%d\n",mi);
}
return 0;
}