首页 > 代码库 > POJ 2485 Highways (kruskal 最小生成树)
POJ 2485 Highways (kruskal 最小生成树)
Highways
POJ 2485
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
求连接所有结点的最小生成树 并得出最小生成树求其中最大权值
#include<cstdio>#include<iostream>#include<cstring>#include<algorithm>using namespace std;int n,coun;struct road{ int f,t; int w;};road vil[25000+10];int fa[25000+10];int cmp(road a ,road b) {return a.w<b.w;}int find(int x){ return fa[x]==x?x:fa[x]=find(fa[x]);}int Kruskal(){ int ans=-1; for(int i=0;i<coun;i++) fa[i]=i; sort(vil,vil+coun,cmp); for(int i=0;i<coun;i++) { int x=find(vil[i].f); int y=find(vil[i].t); if(x!=y) { fa[x]=y; if(vil[i].w>ans) ans=vil[i].w; } } return ans;}int main(){ int i,j; int t; scanf("%d",&t); while(t--) { scanf("%d",&n); coun=0; for(i=1;i<=n;i++) { for(j=1;j<=n;j++) { int waste; scanf("%d",&waste); if(i<j) { vil[coun].f=i; vil[coun].t=j; vil[coun].w=waste; coun++; } } } int ans=Kruskal(); printf("%d\n",ans); } return 0;}
POJ 2485 Highways (kruskal 最小生成树)