【POJ 3255】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

Hint

Two routes: 1 -> 2 -> 4 (length 100+200=300) and 1 -> 2 -> 3 -> 4 (length 100+250+100=450)


【分析】

题目大意:给出一张无向图,边带权,求 1 1 n n 的次短路

次短路模板题

次短路可以理解成在最短路的情况下换一些边

那么我们先分别处理出从 1 , n 1,n 开始的最短路

那么,对于一条边 ( x , y ) (x,y) ,如果 d 1 , x + w x , y + d n , y d 1 , n d_{1,x}+w_{x,y}+d_{n,y}\ne d_{1,n} ,那它就不在最短路上,就可以用它来更新答案

剩下的就是最短路模板啦,还是很简单的


【代码】

#include<queue>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define N 5005
#define M 200005
#define inf 0x3f3f3f3f
using namespace std;
int n,m,t;
int v[M],w[M],nxt[M];
int d[2][N],first[N];
priority_queue<pair<int,int> >q;
void add(int x,int y,int z)
{
	t++;
	nxt[t]=first[x];
	first[x]=t;
	v[t]=y;
	w[t]=z;
}
void dijkstra(int s)
{
	int x,y,i,j;
	int temp=(s==1?0:1);
	memset(d[temp],127/3,sizeof(d[temp]));
	q.push(make_pair(0,s));d[temp][s]=0;
	while(!q.empty())
	{
		x=q.top().second;q.pop();
		for(i=first[x];i;i=nxt[i])
		{
			y=v[i];
			if(d[temp][y]>d[temp][x]+w[i])
			{
				d[temp][y]=d[temp][x]+w[i];
				q.push(make_pair(-d[temp][y],y)); 
			}
		}
	}
}
int main()
{
	int x,y,z,i,j;
	scanf("%d%d",&n,&m);
	for(i=1;i<=m;++i)
	{
		scanf("%d%d%d",&x,&y,&z);
		add(x,y,z),add(y,x,z);
	}
	dijkstra(1);
	dijkstra(n);
	int Min=inf;
	for(i=1;i<=n;++i)
	  for(j=first[i];j;j=nxt[j])
	    if(d[0][i]+w[j]+d[1][v[j]]!=d[0][n])
	      Min=min(Min,d[0][i]+w[j]+d[1][v[j]]);
	printf("%d",Min);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/forever_dreams/article/details/83500765
今日推荐