Highways(prim——最小生成树)

来源:互联网 发布:凡人修真2源码 编辑:程序博客网 时间:2024/04/30 07:52

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

130 990 692990 0 179692 179 0

Sample Output

692

Hint

Huge input,scanf is recommended.


题目大意:

在n个城市之间建高速公路,使得任意两个城市都可以通过高速公路连通,并且建的路最短。要求输出在所有连通相邻两个城市的高速公路里边的最长的那一条公路的长度。

prim算法-------求最小生成树

#include<stdio.h>#include<string.h>/*定义一个比较大的数作为无穷大,赋作不能直接相连的两结点的权值*/#define MAX 0x3f3f3f3f/*N:结点的数目及城市的数目;邻接矩阵(map数组):储存任意两结点间的权值;数组(low):记录当前权值;数组(visited):标记结点是否访问过*/int N,map[505][505],low[505],visited[505];//prim算法求最小生成树void  prim(){int i,j,k,min,pos;//初始化(visited)数组,赋值为零,标记为所以点未访问过memset(visited,0,sizeof(visited));//标记起点已访问visited[0]=1;//记录起点pos=0;//初始化权值数组(low)for(i=0;i<N;i++){low[i]=map[0][i];}//再做N-1次循环,将所以结点加入到生成树中for(i=1;i<N;i++){min=MAX;//遍历权值数组,找到权值最小的结点for(j=0;j<N;j++){if(!visited[j]&&low[j]<=min){min=low[j];//记录最小权值pos=j;//记录相应的结点}}//标记相应的结点即该点已经访问过visited[pos]=1;//更新权值数组(low)for(j=0;j<N;j++){if(!visited[j]&&map[pos][j]<low[j]){                low[j]=map[pos][j];}}}}int main(){    int i,j,T,sum;    scanf("%d",&T);    while(T--)    {        scanf("%d",&N);        //将图表储存在邻接矩阵中        for(i=0;i<N;i++)        {            for(j=0;j<N;j++)            {                scanf("%d",&map[i][j]);            }        }        prim();        //遍历最终的权值数组,找到最大的权值        for(i=0,sum=0;i<N;i++)        {            sum=sum>low[i]?sum:low[i];        }printf("%d\n",sum);    }    return 0;}


0 0
原创粉丝点击