POJ 2485 Highways

来源:互联网 发布:泰克网络实验室怎么样 编辑:程序博客网 时间:2024/06/09 19:20

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.

题意: 第一行是1->1, 1->2, 1->3的距离,求最小生成树中最大边。

题解: Kruskal算法,直接比较就好了。

#include<cstdio>#include<algorithm>using namespace std;const int maxn=510*510;struct node {    int x, y;    int price ;}a[maxn];int vis[510];int  find(int x){    if(vis[x]==x)    return x;    return find(vis[x]);}bool cmp(node a,node b){    return a.price <b.price ;}void join(int a,int b){    int x=find(a);    int y=find(b);    if(x!=y)    vis[x]=y;}int main(){    int t;    scanf("%d",&t);    while(t--)    {        int n;        scanf("%d",&n);        int s,k=0;        for(int i=1;i<=n;i++)        vis[i]=i;        for(int i=1;i<=n;i++)        {            for(int j=1;j<=n;j++)            {                scanf("%d",&s);                a[k].x =i;                a[k].y =j;                a[k++].price =s;            }        }    //  printf("%d\n",k);        sort(a,a+k,cmp);        int dis=0;        for(int i=0;i<k;i++)        {            if(find(a[i].x )!=find(a[i].y ))            {                if(a[i].price>dis)                 dis=a[i].price ;                join(a[i].x ,a[i].y );            }        }        printf("%d\n",dis);    }}