POJ 2485 Prim

来源:互联网 发布:xilinx linux系统类型 编辑:程序博客网 时间:2024/05/17 07:03

题目:

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.

 

题目大意:就是一个岛国没有高速公路,政府想修高速公路,但钱的问题就是想只修几条公路,但是要联通所有的村庄,问你怎么修,该修哪几条路,求出这几条路中最长的那条,其实就是求最小生成树中最大的那条边。

代码:

#include<iostream>#include<string.h>using namespace std;void prim(int **a,int n){    int i,k;    int quan[500];    memset(quan,66537,sizeof(quan));    bool v[500]={0};    v[0]=1;    for(i=1;i<n;i++)    {        v[i]=0;        quan[i]=a[0][i];    }    int sum=0;    for(k=1;k<n;k++)    {        int j,min=65537;        for(i=1;i<n;i++)            if(min>quan[i]&&!v[i]){min=quan[i],j=i;}        if(sum<min)sum=min;        v[j]=1;        for(i=1;i<n;i++)            if(quan[i]>a[j][i]&&!v[i])quan[i]=a[j][i];    }    cout<<sum<<endl;}int main(){    int i,j;    int **a=new int*[500];    for(i=0;i<500;i++)a[i]=new int[500];    int t;    cin>>t;    while(t--)    {        for(i=0;i<500;i++)memset(a[i],65537,sizeof(a[i]));        int n;        cin>>n;        for(i=0;i<n;i++)            for(j=0;j<n;j++)                cin>>a[i][j];        prim(a,n);    }    return 0;}


很容易懂的代码,就没注释了,呵呵........