HDU 1162 Eddy's picture(最小生成树)

题目链接

裸最小生成树。 还好数据小,0ms。

 1 #include <stdio.h>

 2 #include <stdlib.h>

 3 #include <string.h>

 4 #include <math.h>

 5 int o[101],num;

 6 double sum;

 7 struct edge

 8 {

 9     int sv,ev;

10     double w;

11 } p[10000];

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

13 {

14     return (*(struct edge *)a).w>(*(struct edge *)b).w? 1:-1;

15 }

16 int find(int x)

17 {

18     while(x != o[x])

19     {

20         x = o[x];

21     }

22     return x;

23 }

24 void merge(int x,int y,double w)

25 {

26     x = find(x);

27     y = find(y);

28     if(x != y)

29     {

30         o[x] = y;

31         sum += w;

32         num ++;

33     }

34 }

35 int main()

36 {

37     int i,j,n;

38     double x1[101],y1[101];

39     while(scanf("%d",&n)!=EOF)

40     {

41         sum = 0;

42         for(i = 1; i <= n; i ++)

43             o[i] = i;

44         for(i = 1; i <= n; i ++)

45         {

46             scanf("%lf%lf",&x1[i],&y1[i]);

47         }

48         num = 0;

49         for(i = 1; i <= n-1; i ++)

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

51             {

52                 p[num].sv = i;

53                 p[num].ev = j;

54                 p[num].w = sqrt((x1[i]-x1[j])*(x1[i]-x1[j])+(y1[i]-y1[j])*(y1[i]-y1[j]));

55                 num ++;

56             }

57         qsort(p,num,sizeof(p[0]),cmp);

58         num = 1;

59         for(i = 0;; i ++)

60         {

61             if(num == n)

62                 break;

63             merge(p[i].sv,p[i].ev,p[i].w);

64         }

65         printf("%.2lf\n",sum);

66     }

67     return 0;

68 }

 

你可能感兴趣的:(最小生成树)