天天看點

Highways(prim——最小生成樹)

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.

題目大意:

在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;
}
           

繼續閱讀