poj 1125 求最短路径

题目大意:给出一组顶点和各顶点到达其他的直接距离,求每个点到其他点的最短距离中的最大值,然后在这些点里面最大值里面的最小值,而且要注意这个点要是能到达其他每个点。

解题思路:floyd算法求出每对点之间的最小值,然后枚举每个顶点,就这个顶点到其他点的距离中的最大值,而且要保证这个顶点都能到达其他每个点,求这些最大值里面的最小值和相应顶点。

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

using namespace std;

const int maxn = 101;
int graph[maxn][maxn], dp[maxn][maxn];
int n, m;
int main()
{
	
	while(true)
	{
		scanf("%d", &n);
		if(n == 0)
			break;
		memset(graph, -1, sizeof(graph));
		for(int i = 1; i <= n; i++)
		{
			graph[i][i] = 0;
			scanf("%d", &m);
			for(int j = 0; j < m; j++)
			{
				int index, val;
				scanf("%d %d", &index, &val);
				graph[i][index] = val;
			}
		}
		
		for(int k = 1; k <= n; k++)
		{
			for(int i = 1; i <= n; i++)
			{
				for(int j = 1; j <= n; j++)
				{
					if(graph[i][k] != -1 && graph[k][j] != -1)
					{
						if(graph[i][j] == -1)
							graph[i][j] = graph[i][k] + graph[k][j];
						else
							graph[i][j] = min(graph[i][j], graph[i][k] + graph[k][j]);
					}
				}
			}
		}
		
		int index = -1, pre = -1, tmp = -1;
		bool flag = true;
		for(int i = 1; i <= n; i++)
		{
			flag = true;
			tmp = -1; 
			for(int j = 1; j <= n; j++)
			{
				if(i == j)
					continue;
				if(graph[i][j] == -1)
				{
					flag = false;
					break;
				}
				tmp = max(tmp, graph[i][j]);
			}	
			if(!flag)
				continue;
			if(pre == -1)
			{
				pre = tmp;
				index = i;
			}
			else
			{
				if(pre > tmp)
				{
					pre = tmp;
					index = i;
				}
			}
		}
		
		if(index == -1)
		{
			printf("disjoint\n");
			continue;
		}
		printf("%d %d\n", index, pre);
	}
	
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值