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.
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.
1 3 0 990 692 990 0 179 692 179 0Sample Output
692
這道題 說實話,沒看懂題目的意思,所以就去看了下博客,看了下別人寫的題意(英語真的越來越渣了QAQ),不過在知道意思後其實也挺簡單的,就是有點麻煩,這道題的意思其實就是:
給你N個村莊,然後吧每個村莊之間的距離用個二維數組表現出來 拿例子來說就是 1 和1 的距離是0 , 1和2的距離是990, 1和3的距離是692 ,第二行就是 2和1的距離是990
2和2 的距離是0 以此類推 這樣應該就理解了 那麼 這道題的最後目的其實是讓我們求出最優連通方案中 一條最長的距離是多少,這個不好理解 但其實你把例子畫一下也就懂了,真的不是文字就表達清楚了QAQ
這道題的難點有兩個,第一個是如何把給的數據轉化爲我們希望得到的數據,還有就是如和求出最長的那條,當然,代碼如下,自己體會吧(抽時間把解釋補上去QAQ):
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<math.h>
#define MAX 10000010
using namespace std;
int y[510][510];
int par[MAX];
int heigh[MAX];
int t;
struct ege{
int u,v,w;
}G[MAX];
void chushihua(int n)
{
for(int i=0;i<=n;i++)
{
par[i]=i;
heigh[i]=0;
}
}
int find(int n)
{
int r=n;
while(par[r]!=r)
r=par[r];
return r;
}
void unite(int x,int y)
{
x=find(x);
y=find(y);
if(x==y)
return ;
if(heigh[y]>heigh[x])
par[x]=y;
else
{
par[y]=x;
if(heigh[x]==heigh[y])
heigh[x]++;
}
}
bool same(int x,int y)
{
return find(x)==find(y);
}
bool cmp(ege R,ege b)
{
return R.w<b.w;
}
int kruskal()
{
sort(G+1,G+t+1,cmp);
chushihua(t);
int ans=0;
int mk=0;
for(int i=1;i<=t;i++)
{
if(!same(G[i].u,G[i].v))
{
unite(G[i].u,G[i].v);
mk=max(mk,G[i].w);
ans+=G[i].w;
}
}
return mk;
}
int main()
{
int n;
scanf("%d",&n);
while(n--)
{ int m;
scanf("%d",&m);
for(int i=1;i<=m;i++)
{
for(int j=1;j<=m;j++)
{
scanf("%d",&y[i][j]);
}
}
t=0;
for(int k=1;k<=m-1;k++)
{
for(int l=k+1;l<=m;l++)
{
t++;
G[t].u=k;
G[t].v=l;
G[t].w=y[k][l];
}
}
int k;
k=kruskal();
printf("%d\n",k);
}
return 0;
}