最小生成树(kruskal算法)

来源:互联网 发布:java手机色游戏破解版 编辑:程序博客网 时间:2024/05/17 15:16
<span style="font-family:Arial, Helvetica, sans-serif;FONT-SIZE: 18pt">Highways</span>
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 20119 Accepted: 9322

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.

Source

POJ Contest,Author:Mathematica@ZSU



#include <stdio.h>#include <algorithm>using namespace std;//sort函数是stl中的struct graph{ int r1,r2,cost;//首、尾节点、权值}a[250000];int p[501];int n,m,t;bool cmp(graph a,graph b){ return a.cost<b.cost;//sort中的升序排列~~}void init(){ int i; for(i=1;i<=n;i++)  p[i]=i;//并查集的初始化}int find(int x){ if(x!=p[x]) p[x]=find(p[x]);//带有路径压缩的找根节点 return p[x];}void un(int x,int y){ p[x]=y;//已经在find的时候路径压缩了,所以这里的union随便谁赋给谁都行}int kruskal(){ int j,total,b1,b2; init(); total=0;//计数,返回的是n-1的那个,也就是最小生成树中最大的那条边~~ j=1;//a[]数组计数的~ while(1) {  b1= find(a[j].r1);  b2= find(a[j].r2);  if(b1!=b2)//判断,如果构不成回路的话,就是不在并查集的一个集合中要union  {   un(b1,b2);   total++;   if(total==n-1)    return a[j].cost;  }  j++;//每次都取数组中的下一个~ }}int main(){ int i,j,c,end; scanf("%d",&t); while(t--) {  scanf("%d",&n);        m=0;  for(i=1;i<=n;i++)   for(j=1;j<=n;j++)//读入   {       scanf("%d",&c);       if(i<j)     {     m++;     a[m].r1=i;                    a[m].r2=j;     a[m].cost=c;    }   }      sort(a+1,a+m+1,cmp);//cmp在上面,是按cost从小到大排序     end=kruskal();     printf("%d\n",end); } return 1;}


0 0
原创粉丝点击