码迷,mamicode.com
首页 > 数据库 > 详细

POJ 3255 Roadblocks (次短路问题)

时间:2014-07-09 11:28:13      阅读:245      评论:0      收藏:0      [点我收藏+]

标签:poj   算法   图论   次短路   

解法有很多奇葩的地方,比如可以到达终点再跳回去再跳回来(比如有两个点)。。。。反正就是不能有最短路,不过没关系,算法都能给出正确结果

思想:和求最短路上的点套路一样,spfa先正着求一次,再反着求一次最短路,然后枚举每条边<i,j>找dist_zheng[i] + len<i,j> + dist_fan[j]的第二小值即可!注意不能用邻接矩阵,那样会MLE,应该用邻接表


/*
poj    3255
3808K	266MS
*/

#include<cstdio>
#include<cstring>
#include<queue>
#include<iostream>

#define MAXN 200005
#define MAX_INT 2147483647

using namespace std;

int last[5005], dist_1[5005], dist_2[5005], n, m, gra[5005][5005];
bool mark[MAXN];

struct node
{
	int u;
	int v;
	int w;
	int next;
	node()
	{
		u = v = w = next = 0;
	}
}edge[MAXN];

void spfa( int dist[5005], int s )
{
	queue<int>myQueue;
	dist[s] = 0;
	memset(mark, false, sizeof(mark));
	mark[s] = true;
	myQueue.push(s);
	while( !myQueue.empty() )
	{
		int x = myQueue.front();
		myQueue.pop();
		mark[x] = false;
		int t = last[x];
		while( t )
		{
			if( dist[ edge[t].v ] > dist[x] + edge[t].w  )
			{
				dist[ edge[t].v ] = dist[x] + edge[t].w;
				if( !mark[ edge[t].v ] )
					myQueue.push( edge[t].v );
			}
			t = edge[t].next;
		}
	}
}

int main()
{
	cin >> n >> m;
	for(int i = 1;i <= m;i ++)
	{
		int a, b, c;
		scanf("%d %d %d", &a, &b, &c);
		edge[i].u = edge[i + m].v = a;
		edge[i].v = edge[i + m].u = b;
		edge[i].w = edge[i + m].w = c;
		edge[i].next = last[a];
		last[a] = i;
		edge[i + m].next = last[b];
		last[b] = i + m;
	}
	memset( dist_1, 1, sizeof(dist_1) );
	spfa( dist_1, 1 );
	memset( dist_2, 1, sizeof(dist_2) );
	spfa( dist_2, n );
	int ans = MAX_INT, tmp = MAX_INT;
	for(int i = 1;i <= n;i ++)
	{
		int t = last[i];
		while( t )
		{
			if( dist_1[i] + dist_2[ edge[t].v ] + edge[t].w < tmp )
			{
				ans = tmp;
				tmp = dist_1[i] + dist_2[ edge[t].v ] + edge[t].w;
			}
			else if( dist_1[i] + dist_2[ edge[t].v ] + edge[t].w < ans 
					&& dist_1[i] + dist_2[ edge[t].v ] + edge[t].w != tmp )
				ans = dist_1[i] + dist_2[ edge[t].v ] + edge[t].w;
			t = edge[t].next;
		}
	}
	cout << ans << endl;
	return 0;
}


POJ 3255 Roadblocks (次短路问题),布布扣,bubuko.com

POJ 3255 Roadblocks (次短路问题)

标签:poj   算法   图论   次短路   

原文地址:http://blog.csdn.net/u013687632/article/details/37569463

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!