最小生成树
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
using namespace std;
int t,n,cnt;
double cost;
int mapx[1005],mapy[1005];
int f[1005];
struct edge{
int a,b;
double e;
} map[1000000];
double cal(int& a,int& b)
{
return sqrt(1.0*( (mapx[a]-mapx[b])*(mapx[a]-mapx[b]) + (mapy[a]-mapy[b])*(mapy[a]-mapy[b]) ));
}
bool cmp(edge a,edge b)
{
return a.e<b.e;
}
int sf(int x){
return x==f[x]? x: f[x]=sf(f[x]);
}
int main()
{
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
for(int i=1;i<=n;i++) f[i]=i;
cnt=0;
for(int i=1;i<=n;i++)
{
scanf("%d%d",&mapx[i],&mapy[i]);
for(int j=1;j<i;j++)
{
double e=cal(i,j);
if(e>=10&&e<=1000)
{
map[cnt].a=j;
map[cnt].b=i;
map[cnt].e=e;
cnt++;
}
}
}
sort(map,map+cnt,cmp);
cost=0;
int fa,fb;
for(int i=0;i<cnt;++i)
{
fa=sf(map[i].a);
fb=sf(map[i].b);
if(fa!=fb)
{
f[fa]=fb;
cost+=map[i].e;
}
}
int p=0;
for(int i=1;i<=n;i++) if(sf(f[i])==i) p++;
if(p>1) puts("oh!");
else printf("%.1lf\n",cost*100);
}
}
原文:http://www.cnblogs.com/nicetomeetu/p/5551369.html