2 2 10 10 20 20 3 1 1 2 2 1000 1000
1414.2 oh!
在 查找根节点的过程中注意数组的越界(稍不留神那个你就越雷池半步了,我也是醉了),这道题是我以16次Runtime Error(STACK_OVERFLOW) 的血的教训得来的额,以后我得注意查找根节点时最好需要路径压缩一下,这下子终于体会到路径压缩的好处了
/*AC*/
#include<cstdio>
#include<cmath>}
/*Runtime Error
(STACK_OVERFLOW)*/
#include<cstdio>
#include<cmath>
#include<cstring>
#include<cstdlib>
#include<algorithm>
using namespace std;
const int M=105;
int pre[M];
struct node
{
int start;
int end;
}island[M];
struct dis
{
int x;
int y;
double value;
}num[M*M];
int find(int x)
{
return x==pre[x]?x:pre[x]==find(pre[x]);//没有经过路径压缩
}
void merge(int x,int y)
{
int fx=find(x);
int fy=find(y);
if(fx!=fy)
pre[fx]=fy;
}
double Dis(node a,node b)
{
return sqrt(1.0*((a.start-b.start)*(a.start-b.start)+(a.end-b.end)*(a.end-b.end)));
}
int jude(double d)
{
if(d>=10&&d<=1000)
return 1;
else
return 0;
}
int cmp(dis a,dis b)
{
return a.value<b.value;
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
int C,i,j,k;
scanf("%d",&C);
if(C==1)
{
printf("0.0\n");
continue;
}
for(i=0;i<=M;i++)
pre[i]=i;
for(i=1;i<=C;i++)
scanf("%d%d",&island[i].start,&island[i].end);
k=0;
memset(num,0,sizeof(num));
for(i=1;i<=C;i++)
for(j=i+1;j<=C;j++)
{
double dis=Dis(island[i],island[j]);
if(jude(dis))
{
num[k].x=i;
num[k].y=j;
num[k].value=dis;
k++;
}
}
sort(num,num+k,cmp);
double ans=0.0;
for(i=0;i<k;i++)
if(find(num[i].x)!=find(num[i].y)&&jude(num[i].value))
{
merge(num[i].x,num[i].y);
ans+=num[i].value;
}
int count=0;
for(i=1;i<=C;i++)
{
if(pre[i]==i)
count++;
if(count>1)
break;
}
if(count>1)
printf("oh!\n");
else
printf("%.1lf\n",ans*100);
}
return 0;
}
原文地址:http://blog.csdn.net/lh__huahuan/article/details/44786513