初级->图算法->最小生成树 poj 2485 Highways

来源:互联网 发布:部落冲突王的升级数据 编辑:程序博客网 时间:2024/04/28 12:17
Highways
Time Limit: 1000MSMemory Limit: 65536KTotal Submissions: 16882Accepted: 7897

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
 

题意:一个完全图。每两个村子的高速公路有一个距离(自身到自身是0),就是裸的最小生成树,只不过题目让我们求的是最小生成树的所有路径中最长的那条。我是开个数组存下所有求得的路径,最后求其最大的那个。

// prim算法

 
#include<iostream>#include<cstring>#include<cstdio>using namespace std;int map[501][501];int main(){    int t,n,i,j,c,min,pos;    int vist[501],dist[501],a[500];    cin>>t;    scanf("\n");    while(t--)    {        cin>>n;        for(i=1;i<=n;i++)        for(j=1;j<=n;j++)        {            cin>>c;            map[i][j]=c;        }        a[1]=0;        memset(vist,0,sizeof(vist));        for(i=1;i<=n;i++)        dist[i]=map[1][i];        vist[1]=1;        for(i=2;i<=n;i++)        {            min=9999999;            for(j=1;j<=n;j++)            if(!vist[j]&&min>dist[j])            {                min=dist[j];                pos=j;            }            a[i]=min;            vist[pos]=1;            for(j=1;j<=n;j++)            if(!vist[j]&&dist[j]>map[pos][j])            dist[j]=map[pos][j];        }        min=a[1];        for(i=2;i<=n;i++)        if(min<a[i])        min=a[i];        cout<<min<<endl;    }    return 0;}