您的位置:首页 > 其它

hdu 1595 find the longest of the shortest (spfa)

2014-12-04 20:31 302 查看
记录最短路上的路径依次枚举删掉,看看剩下的最短路最大值是多少。

#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<queue>

using namespace std;

#define N 1005
const int inf = 1 << 28;

struct node{
    int to, nxt, w;
}e[N*N];

int dis
, vis
;
int head
;
int pre
;
int n, m;
int cnt;
int a

;

void init()
{
    memset(head, -1, sizeof(head));
    memset(pre, 0, sizeof(pre));
    memset(a, 0, sizeof(a));
    cnt = 0;
}

void add( int u, int v, int w )
{
    e[cnt].to = v;
    e[cnt].w = w;
    e[cnt].nxt = head[u];
    head[u] = cnt++;
}

void spfa()
{
	queue<int> q;
	while( !q.empty() )
		q.pop();
	for( int i = 1; i <= n; i++ )
	{
		vis[i] = 0;
		dis[i] = inf;
	}
	vis[1] = 1;
	dis[1] = 0;
	q.push(1);
	while( !q.empty() )
	{
		int now = q.front();
		q.pop();
		vis[now] = 0;
		for( int i = head[now]; ~i; i = e[i].nxt )
		{
			int to = e[i].to;
			if( dis[to] > dis[now] + e[i].w )
			{
				dis[to] = dis[now] + e[i].w;
				pre[to] = now;
				if( !vis[to] )
				{
					vis[to] = 1;
					q.push(to);
				}
			}
		}
	}
}

void spfa1()
{
	queue<int> q;
	while( !q.empty() )
		q.pop();
	for( int i = 1; i <= n; i++ )
	{
		vis[i] = 0;
		dis[i] = inf;
	}
	vis[1] = 1;
	dis[1] = 0;
	q.push(1);
	while( !q.empty() )
	{
		int now = q.front();
		q.pop();
		vis[now] = 0;
		for( int i = head[now]; ~i; i = e[i].nxt )
		{
			int to = e[i].to;
			if( a[now][to] && dis[to] > dis[now] + e[i].w )
			{
				dis[to] = dis[now] + e[i].w;
				//pre[to] = now;
				if( !vis[to] )
				{
					vis[to] = 1;
					q.push(to);
				}
			}
		}
	}
}

int main()
{
	while(~scanf("%d%d", &n, &m))
	{
		init();
		int u, v, w;
		while(m--)
		{
			scanf("%d%d%d", &u, &v, &w);
			add(u, v, w);
			add(v, u, w);
			a[u][v] = a[v][u] = 1;
		}
		int ans = 0;
		spfa();
		for( int i = n; i != 0; i = pre[i])
		{
			a[i][pre[i]] = a[pre[i]][i] = 0;
			spfa1();
			ans = max(ans, dis
);
			a[i][pre[i]] = a[pre[i]][i] = 1;
		}
		printf("%d\n", ans);
	}
	return 0;
}


某处vis标记写错改了好久好久好久好久好久好久好久好久好久好久好久好久好久好久好久好久好久好久好久好久...
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐