POJ 2485:Highways:典型prim最小生成树(2)

Highways
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 21456   Accepted: 9884

Description

The island nation of Flatopia is perfectly flat. Unfortunately, Flatopia has no public highways. So the traffic is difficult in Flatopia. The Flatopian government is aware of this problem. They're planning to build some highways so that it will be possible to drive between any pair of towns without leaving the highway system. 

Flatopian towns are numbered from 1 to N. Each highway connects exactly two towns. All highways follow straight lines. All highways can be used in both directions. Highways can freely cross each other, but a driver can only switch between highways at a town that is located at the end of both highways. 

The Flatopian government wants to minimize the length of the longest highway to be built. However, they want to guarantee that every town is highway-reachable from every other town.

Input

The first line of input is an integer T, which tells how many test cases followed. 
The first line of each case is an integer N (3 <= N <= 500), which is the number of villages. Then come N lines, the i-th of which contains N integers, and the j-th of these N integers is the distance (the distance should be an integer within [1, 65536]) between village i and village j. There is an empty line after each test case.

Output

For each test case, you should output a line contains an integer, which is the length of the longest road to be built such that all the villages are connected, and this value is minimum.

Sample Input

1

3
0 990 692
990 0 179
692 179 0

Sample Output

692

Hint

Huge input,scanf is recommended.

Source

POJ Contest,Author:Mathematica@ZSU
同样非常典型的prim算法,计算最小生成树,该题目的问法揭示了最小生成树的本质:使连接的生成树最长路径最短,动态规划思想实现就是prim算法。将上一个题目的程序核心不变,稍加修改输入输出,AC!
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define maxn 10000
int t;
int n,d[505],a[505][505],use[505];
void init()
{
	int i,j;
	scanf("%d",&n);
	for(i=0;i<n;i++)
		d[i]=use[i]=0;
	for(i=0;i<n;i++)
		for(j=0;j<n;j++)
			scanf("%d",&a[i][j]);
}
void prim()
{
	int i,j;
	int minc,mind;
	use[0]=1;
	d[0]=0;
	for(i=1;i<n;i++)
		d[i]=a[0][i];
	for(j=0;j<n-1;j++)
	{
		minc=maxn;
		for(i=0;i<n;i++)
		{
			if(!use[i]&&minc>d[i])
			{
				minc=d[i];
				mind=i;
			}
		}
		if(minc!=maxn)
		{
			use[mind]=1;
			for(i=0;i<n;i++)
			{
				if(!use[i]&&d[i]>a[mind][i])
					d[i]=a[mind][i];
			}
		}
	}
}
void print()
{
	int i,j;
	int sum=0;
	for(i=1;i<n;i++)
		sum=d[i]>sum?d[i]:sum;
	printf("%d\n",sum);
}
int main()
{
	int i,j;
	while(scanf("%d",&t)!=EOF&&t)
	{
		while(t--)
		{
		init();
		prim();
		print();
		}
	}
	return 0;
}


你可能感兴趣的:(POJ 2485:Highways:典型prim最小生成树(2))