題目:
相信大家都聽說一個“百島湖”的地方吧,百島湖的居民生活在不同的小島中,當他們想去其他的小島時都要通過劃小船來實現。現在政府決定大力發展百島湖,發展首先要解決的問題當然是交通問題,政府決定實現百島湖的全暢通!經過考察小組RPRush對百島湖的情況充分了解後,決定在符合條件的小島間建上橋,所謂符合條件,就是2個小島之間的距離不能小於10米,也不能大於1000米。當然,爲了節省資金,只要求實現任意2個小島之間有路通即可。其中橋的價格爲 100元/米。
Input
輸入包括多組數據。輸入首先包括一個整數T(T <= 200),代表有T組數據。
每組數據首先是一個整數C(C <= 100),代表小島的個數,接下來是C組座標,代表每個小島的座標,這些座標都是 0 <= x, y <= 1000的整數。
Output
每組輸入數據輸出一行,代表建橋的最小花費,結果保留一位小數。如果無法實現工程以達到全部暢通,輸出”oh!”.
Sample Input
2 2 10 10 20 20 3 1 1 2 2 1000 1000
Sample Output
1414.2 oh!
只需要在加入邊結構體的時候多加一個判斷即可,由於邊長的約數可能造成邊數量的缺失,從而導致提前退出Kruskal的循環,因此在最後判斷一下countt的個數是否爲n-1即可;
代碼:
#include<stdio.h>
#include<algorithm>
#include<math.h>
using namespace std;
const int maxn=105;
struct node
{
double x,y;
}dian[maxn];
struct edge
{
int u,v;
double w;
}e[maxn*maxn];
int f[maxn];
int t,n,m,countt;
double sum;
void intt()
{
for(int i=0;i<=n;i++)
f[i]=i;
}
int getf(int v)
{
if(f[v]==v)
return v;
else
{
f[v]=getf(f[v]);
return f[v];
}
}
int mergee(int a,int b)
{
int t1=getf(a);
int t2=getf(b);
if(t1!=t2)
{
f[t2]=t1;
return 1;
}
return 0;
}
bool cmp(const edge &a,const edge &b)
{
return a.w<b.w;
}
int main()
{
scanf("%d",&t);
while(t--)
{
m=0;
scanf("%d",&n);
for(int i=0;i<n;i++)
scanf("%lf %lf",&dian[i].x,&dian[i].y);
for(int i=0;i<n;i++)
{
for(int j=0;j<i;j++)
{
double z;
z=sqrt((dian[i].x-dian[j].x)*(dian[i].x-dian[j].x)+
(dian[i].y-dian[j].y)*(dian[i].y-dian[j].y));
if(z>=10&&z<=1000)
{
e[m].u=j;
e[m].v=i;
e[m++].w=z;
}
}
}
sort(e,e+m,cmp);
countt=0;
sum=0;
intt();
for(int i=0;i<m;i++)
{
if(mergee(e[i].u,e[i].v))
{
countt++;
sum+=e[i].w;
}
if(countt==n-1)
break;
}
if(countt==n-1)
printf("%0.1lf\n",sum*100);
else
printf("oh!\n");
}
}