Uva10034(Freckles)

最基础的最小生成树,简单题。

View Code
 1 #include <stdio.h>

 2 #include <math.h>

 3 #include <stdlib.h>

 4 #define D(x1,y1,x2,y2) (sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)))

 5 #define N 100

 6 #define M 5000

 7 struct node

 8 {

 9     int a,b;

10     double d;

11 }edge[M];

12 int n,m;

13 double x[N],y[N];

14 int p[M];

15 void make_set()

16 {

17     int i;

18     for(i=0;i<m;i++)  p[i]=i;

19 }

20 int find_set(int i)

21 {

22     return i==p[i]?p[i]:(p[i]=find_set(p[i]));

23 }

24 int union_set(int i,int j)

25 {

26     i=p[i],j=p[j];

27     p[j]=i;

28 }

29 int cmp(void const *a,void const *b)

30 {

31     return ((struct node*)a)->d-((struct node*)b)->d>0?1:-1;

32 }

33 int main()

34 {

35     int t,i,j;

36     double ans;

37     scanf("%d",&t);

38     while(t--)

39     {

40         scanf("%d",&n);

41         for(i=0;i<n;i++)

42         {

43             scanf("%lf%lf",&x[i],&y[i]);

44         }

45         m=0;

46         for(i=0;i<n;i++)

47         {

48             for(j=i+1;j<n;j++)

49             {

50                 edge[m].a=i,edge[m].b=j;

51                 edge[m++].d=D(x[i],y[i],x[j],y[j]);

52             }

53         }

54         make_set();

55         qsort(edge,m,sizeof(edge[0]),cmp);

56         for(i=0,ans=0;i<m;i++)

57         {

58             if(find_set(edge[i].a)==find_set(edge[i].b))    continue;

59             union_set(edge[i].a,edge[i].b);

60             ans+=edge[i].d;

61         }

62         printf("%.2lf\n",ans);

63         if(t)   printf("\n");

64     }

65     return 0;

66 }

 

你可能感兴趣的:(uva)