hdu1875

http://acm.hdu.edu.cn/showproblem.php?pid=1875

2

2

10 10

20 20

3

1 1

2 2

1000 1000

给定坐标

  1 //最小生成树
  2 #include<iostream>
  3 #include<stdio.h>
  4 #include<math.h>
  5 #include<string.h>
  6 #include<stdlib.h>
  7 using namespace std;
  8 const int N=5005;
  9 int father[N];
 10 int n,m,g;
 11 struct stu{
 12     int n;
 13     int x;
 14     int y;
 15 }q[N];
 16 struct ln{
 17     int u;
 18     int v;
 19     double w;
 20 }p[N];
 21 
 22 int cmp(const void *a,const void *b)
 23 {
 24     return (*(struct ln*)a).w >(*(struct ln*)b).w ?1:-1;
 25 }
 26 
 27 int find(int x)
 28 {
 29     if(father[x]!=x)
 30     father[x]=find(father[x]);
 31     return father[x];
 32 }
 33 int make(int a,int b)
 34 {
 35     int h=0;
 36     int f1=find(a);
 37     int f2=find(b);
 38     if(f1<f2)
 39     {
 40         father[f2]=f1;
 41         h=1;
 42     }
 43     else if(f1>f2)
 44     {
 45         father[f1]=f2;
 46         h=1;
 47     }
 48     return h;
 49 }
 50 
 51 double kruskal()
 52 {
 53     double s=0;
 54     int k=0;
 55     for(int i=0;i<m;i++)
 56     {
 57         if(make(p[i].u,p[i].v))
 58         {
 59             if(p[i].w==5000)
 60             g=1;
 61             s+=p[i].w;
 62             k++;
 63         }
 64         if(k==n-1)
 65         return s*100;
 66     }
 67     return s*100;
 68 }
 69 
 70 void zuhe()//道路分析
 71 {
 72     int k=0;
 73     for(int i=1;i<=n;i++)
 74     {
 75         for(int j=i+1;j<=n;j++,k++)
 76         {
 77             p[k].u=i;
 78             p[k].v=j;
 79             p[k].w=sqrt((q[i].x-q[j].x)*(q[i].x-q[j].x)+(q[i].y-q[j].y)*(q[i].y-q[j].y));
 80             if(p[k].w<10 || p[k].w>1000)
 81             {
 82                 p[k].w=5000;
 83             }
 84             //printf("%d %d %lf
",p[k].u,p[k].v,p[k].w);
 85         }
 86     }
 87 }
 88 
 89 int main()
 90 {
 91     //freopen("in.txt","r",stdin);
 92     int t;
 93     double s;
 94     scanf("%d",&t);
 95     while(t--)
 96     {
 97         g=0;
 98         scanf("%d",&n);
 99         m=n*(n-1)/2;
100         for(int i=1;i<=n;i++)
101         {
102             father[i]=i;
103         }
104         for(int i=1;i<=n;i++)
105         {
106             q[i].n=i;
107             scanf("%d%d",&q[i].x,&q[i].y);
108         }
109         zuhe();
110         qsort(p,m,sizeof(struct ln),cmp);
111         s=kruskal();
112         if(g==1)
113         {
114             printf("oh!
");
115             continue;
116         }
117         printf("%.1lf
",s);
118     }
119     return 0;
120 }
原文地址:https://www.cnblogs.com/xuesen1995/p/4515480.html