POJ2485Highways(Kruskal算法)

来源:互联网 发布:c 编程例子 编辑:程序博客网 时间:2024/06/03 20:17

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个节点以及n个边,求最小生成树生成后,最长的一条边是多少.

#include<cstdio>#include<cstring>#include<algorithm>using namespace std;int par[550];struct node{int u,v,w;}arr[300000];int n,i,j;void init(){for(i=1;i<=n;i++)par[i]=i;}bool cmp(node a,node b){return a.w< b.w;};int find(int x){if(x==par[x])return x;elsereturn par[x]=find(par[x]);}int unite(int x,int y){int fx=find(x);int fy=find(y);if(fx!=fy){par[fy]=fx;return 1;}return 0;}int main(){int t,num,l,Max;scanf("%d",&t);while(t--){scanf("%d",&n);l=1;Max=0;int ant=0;for(i=1;i<=n;i++)for(j=1;j<=n;j++){scanf("%d",&num);//此题输入和模板题有点不一样,除了这点,剩下就是模板了 arr[l].u=i;arr[l].v=j;arr[l].w=num;l++;}sort(arr+1,arr+l,cmp);init();for(i=1;i<l;i++){if(unite(arr[i].u,arr[i].v)){if(Max<arr[i].w)Max=arr[i].w;ant++;}if(ant==n-1)break;}printf("%d\n",Max);}}


0 0
原创粉丝点击