Language:
Roadblocks
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个点 m条无向边 从点1走到点n 求出次短路径的长度
次短路指的是比最短路长比其他的短
用数组d存储点1到其他点的最短路径长度 用数组rd存储点n到其他点的最短路径长度
然后枚举每条边 两个短点分别到起点终点的最短长度加上这条边的长度 记录次短路径的值
#include <cstdio>
#include <iostream>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <string.h>
#include <string>
#include <vector>
#include <queue>
#define MEM(a,x) memset(a,x,sizeof a)
#define eps 1e-8
#define MOD 10009
#define MAXN 5010
#define MAXM 100010
#define INF 99999999
#define ll __int64
#define bug cout<<"here"<<endl
#define fread freopen("ceshi.txt","r",stdin)
#define fwrite freopen("out.txt","w",stdout)
using namespace std;
struct Edge
{
int v,w,next;
}edge[MAXM*2];
int d[MAXN],rd[MAXN];
int tot,head[MAXN];
int vis[MAXN];
int n,m;
void init()
{
tot=0;
MEM(head,-1);
for(int i=0;i<=n;i++)
d[i]=rd[i]=INF;
}
void addedge(int u,int v,int w)
{
edge[tot].v=v;
edge[tot].w=w;
edge[tot].next=head[u];
head[u]=tot++;
}
void SPFA(int s,int dis[])
{
int u,v;
queue<int> q;
MEM(vis,0);
dis[s]=0; vis[s]=1;
q.push(s);
while(!q.empty())
{
u=q.front(); q.pop();
vis[u]=0;
for(int i=head[u];i!=-1;i=edge[i].next)
{
v=edge[i].v;
if(dis[u]+edge[i].w<dis[v])
{
dis[v]=dis[u]+edge[i].w;
if(!vis[v])
{
vis[v]=1;
q.push(v);
}
}
}
}
}
int main()
{
// fread;
while(scanf("%d%d",&n,&m)!=EOF)
{
init();
while(m--)
{
int u,v,w;
scanf("%d%d%d",&u,&v,&w);
addedge(u,v,w);
addedge(v,u,w);
}
SPFA(1,d);
SPFA(n,rd);
int ans=INF;
for(int i=1;i<=n;i++)
{
for(int j=head[i];j!=-1;j=edge[j].next)
{
int v=edge[j].v;
int w=edge[j].w;
int tmp=d[i]+rd[v]+w;
if(tmp>d[n]&&ans>tmp)
ans=tmp;
}
}
printf("%d\n",ans);
}
return 0;
}