题目:
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
Hint
Two routes: 1 -> 2 -> 4 (length 100+200=300) and 1 -> 2 -> 3 -> 4 (length 100+250+100=450)
题意:
给出一些点和它们之间的距离,求从1号点到n号点次短路的距离
思路:
1到n的次短路长度必然产生于:从1走到x的最短路+e[x][y]+y到n的最短路
利用spfa算法先求出1到每一个节点的最短路,和n到每一个节点的最短路
然后枚举每一条边作为中间边(x,y)或者(y,x),如果加起来长度等于最短路长度则跳过,否则更新
从1走到x的最短路+e[x][y]+y到n的最短路 给dis1[n] 比较 找大于dis1[n] 且是最小的那一个
代码:
#include<stdio.h>
#include<string.h>
#include<queue>
#include<algorithm>
#define ll long long
#define N 200861
#define inf 0x3f3f3f3f
using namespace std;
int n,m,dis1[N],dis2[N],first[N],k,vis[N];
struct node
{
int u,v,w,next;
}e[N];
void Inint()
{
k=1;
memset(dis1,inf,sizeof(dis1));
memset(dis2,inf,sizeof(dis2));
memset(first,-1,sizeof(first));
}
void add(int u,int v,int w)//邻接表存图
{
e[k].u=u;
e[k].v=v;
e[k].w=w;
e[k].next=first[u];
first[u]=k++;
}
void spfa(int u,int dis[])
{
memset(vis,0,sizeof(vis));
queue<int>q;
dis[u]=0;
vis[u]=1;
q.push(u);
while(!q.empty())
{
u=q.front();
q.pop();
vis[u]=0;
for(int i=first[u];i!=-1;i=e[i].next)
{
int v=e[i].v;
int w=e[i].w;
if(dis[v]>dis[u]+w)
{
dis[v]=dis[u]+w;
if(!vis[v])
{
vis[v]=1;
q.push(v);
}
}
}
}
}
int main()
{
Inint();
scanf("%d%d",&n,&m);
for(int i=1;i<=m;i++)
{
int u,v,w;
scanf("%d%d%d",&u,&v,&w);
add(u,v,w);
add(v,u,w);
}
spfa(1,dis1);//求1到n最短路
spfa(n,dis2);//求n到1最短路
int minn=inf;
for(int i=1;i<=n;i++)
{
for(int j=first[i];j!=-1;j=e[j].next)
{
int v=e[j].v;
int w=e[j].w;
int t=dis1[i]+dis2[v]+w;
if(t>dis1[n]&&t<minn)
minn=t;
}
}
printf("%d\n",minn);
return 0;
}