POJ 2485 Highways
意甲冠军:给你一个数n,代表n村庄,然后你进入到n行n列数,文章i第一线j代表元素i村庄和j从村,要确定您的沟通n维修所需的村庄最短的最大边
思路:用Kruskal算法求
AC代码:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define N 125000 //最多的边数为n*(n-1)/2
int u[N],v[N],w[N],r[N];
int f[520],str[520][520];
int find(int x)
{
if(x!=f[x])
f[x]=find(f[x]);
return f[x];
}
int cmp(const int x,const int y) //间接排序距离
{
return w[x]<w[y];
}
int main()
{
int x,y,sum,e,i,j,n,t,maxx;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
int cnt=0;
memset(str,0,sizeof(str));
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
int val;
scanf("%d",&val);
if(val==0)
continue;
if(!(str[i][j]&&str[j][i]))
{
u[cnt]=i;
v[cnt]=j;
w[cnt++]=val;
str[i][j]=str[j][i]=1;
}
}
for(i=0;i<=n;i++)f[i]=i;
for(i=0;i<=cnt;i++)r[i]=i;
sort(r,r+cnt,cmp);
sum=0;
maxx=0;
for(i=0;i<=cnt;i++)
{
e=r[i];
x=find(u[e]);
y=find(v[e]);
if(x!=y){
maxx=max(maxx,w[e]);
f[x]=y;
}
}
printf("%d\n",maxx);
}
}
版权声明:本文博客原创文章,博客,未经同意,不得转载。

浙公网安备 33010602011771号