POJ - 2485 Highways(最小生成树 prime)

POJ - 2485 Highways(最小生成树)

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.
题意大概:Flatopia政府要在几个城镇之间修建公路,要使得修建公路的长度最小,并且每一个城镇到其他城镇都有连通的公路,就是最小生成树问题。输入T,包括有T组数据,每个测试数据的第一行都是一个整数N(3<=N<=500),表示小镇的数目。接下来N行为邻接矩阵。结果要求输出最小树的最长边。
题目最终目的是让求最小生成树中的最大的那个边。
解题思路:使用prime算法求最小生成树。
Prime代码如下:

#include<stdio.h>
#include<limits.h>
void Prime(); 
int n;
int a[505][505],b[505],c[505];//b[]表示距离,c[]表示是否能够构成最小生成树 
int main()
{
    
    
    int i,j,t;
    scanf("%d",&t);
    while(t--)
    {
    
    
        scanf("%d",&n);
        for(i=0;i<n;i++)
        {
    
    
            for(j=0;j<n;j++)
                scanf("%d",&a[i][j]);
        }
        Prime();
    }
    return 0;
}
void Prime()
{
    
    
	int i,j,sum=0,p,min;
    for(i=0;i<n;i++)
    {
    
    
        c[i]=0; 
        b[i]=a[0][i];
    }
    c[0]=1; 
    b[0]=0;
    for(i=1;i<n;i++)
    {
    
    
        p=-1;
        min=INT_MAX;
        for(j=0;j<n;j++)
        {
    
    
            if(!c[j]&&b[j]<min)
            {
    
    
				min=b[j];
            	p=j;
			}
        }
        c[p]=1;
        if(min>sum)//最小生成树中的最大边 
        {
    
    
        	sum=min;
		}
        for(j=0;j<n;j++)
        {
    
    
            if(!c[j]&&b[j]>a[p][j])
            {
    
    
            	b[j]=a[p][j];
			}
        }
    }
    printf("%d\n",sum);
}

猜你喜欢

转载自blog.csdn.net/weixin_46703995/article/details/107445282