题目来源:POJ - 2485
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.
题目大意就是:用矩阵给出各点之间的距离。采用最短的方式使所有的点连通。输出最佳方式中所需要修建的最长路的距离。
#include<cstdio>
#include<iostream>
#include<cstring>
#include<cmath>
#include<algorithm>
#define MAX 999999
using namespace std;
int pre[100001];
int n,m;
struct node
{
int u,v;
int value;//存储距离
}p[300000];
//这四个函数还是和并查集的一样。
void init(int n)
{
for(int i=1;i<=n;i++)
{
pre[i]=i;
}
}//根据初始化pre[]数组
int find(int x)
{
if(pre[x]==x) return x;
return pre[x]=find(pre[x]);
}//找到根节点
bool cmp (node x,node y)
{
return x.value<y.value;
}
void mix(int x,int y)
{
int fx=find(x);
int fy=find(y);
if(fx!=fy)
{
pre[fy]=fx;
}
}//合并集合。将根节点不同的两个村落连接起来。
int main()
{
int t,s;
cin>>t;
while(t--)
{
scanf("%d",&n);
init(n);
int k=0;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
scanf("%d",&s);
p[k].u =i;
p[k].v =j;//此时的I J 代表了两个村落。
p[k++].value =s;//s代表IJ两个村落间的距离
}
}
sort(p,p+k,cmp);//将所有距离排序,
int dis=0;
for(int i=0;i<k;i++)
{
if(find(p[i].u)!=find(p[i].v))//如果两个村落的根节点不同
{
mix(p[i].u ,p[i].v );//将其连接起来。
if(p[i].value>dis)
dis=p[i].value ;//用于统计最长的那条路。
}
}
printf("%d\n",dis);
}
return 0;
}