HDU 1162 Eddy's picture Kruskal算法

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

题意:

  给出N个坐标,坐标之间的距离就是权值,是个最小生成树的问题,用Kruskal算法做。

 

坑爹:

  一道简单的最小生成树的题目,N个点对应要有N-1条边,没什么难点主要是要细心点就行了。

 

解法:

  Kruskal算法的模版一套上去就行了。

 

View Code
  1 #include<iostream>
  2 #include<math.h>
  3 #include<algorithm>
  4 using namespace std;
  5 
  6 const int maxn = 10000 +10;
  7 
  8 struct edge
  9 {
 10     int start;
 11     int end;
 12     double valve;
 13     friend bool operator < (struct edge a,struct edge b)
 14     {
 15         return a.valve<b.valve;
 16     }
 17 };
 18 struct edge num[maxn];
 19 int father[maxn];
 20 int rank[maxn];
 21 int n;
 22 int k;
 23 
 24 void Make_Set(int x)
 25 {
 26     father[x] = x ;
 27     rank[x] = 0 ;
 28 }
 29 
 30 int find_root(int x)
 31 {
 32     /*if( father[x]!=x){
 33         return father[x] = find_root(father[x]);
 34     }
 35     return  father[x];*/
 36     
 37     if(father[x] == x)
 38     {
 39         return x;
 40     }
 41     else
 42     {
 43         return father[x] = find_root(father[x]);
 44     }
 45     
 46 }
 47 
 48 void Union(int a,int b)
 49 {
 50     int roota;
 51     int rootb;
 52     roota = find_root(a) ;
 53     rootb = find_root(b) ;
 54     
 55     if(roota == rootb )
 56     {
 57         return;
 58     }
 59     
 60     if(rank[roota] > rank[rootb] )
 61     {
 62         father[rootb] = roota;
 63     }
 64     else if(rank[roota] < rank[rootb] )
 65     {
 66         father[roota] = rootb;
 67     }
 68     else
 69     {
 70         father[roota] = rootb;
 71         rank[rootb] ++;
 72     }
 73 }
 74 
 75 double kruskal()
 76 {
 77     double sum=0;
 78     int count=0;
 79     int i;
 80     sort(num,num+k);
 81     for(i=0; i<k && count<=n-1; i++)
 82     {
 83         int a;
 84         int b;
 85         a=num[i].start;
 86         b=num[i].end;
 87         if(find_root(a)!=find_root(b))
 88         {
 89             Union(a,b);
 90             sum+=num[i].valve;
 91             count++;
 92         }
 93     }
 94     return sum;
 95 }
 96 
 97 int main()
 98 {
 99     while(cin>>n)
100     {
101         int i;
102         for(i=0; i<maxn; i++)
103         {
104             Make_Set(i);
105         }
106         double a[maxn];
107         double b[maxn];
108         for(i=0; i<n; i++)
109         {
110             cin>>a[i]>>b[i];
111         }
112         int j;
113         k=0;
114         for(i=0; i<n; i++)
115         {
116             for(j=i+1; j<n; j++)
117             {
118                 num[k].start=i;
119                 num[k].end=j;
120                 num[k++].valve = sqrt( (a[j]-a[i])*(a[j]-a[i]) + (b[j]-b[i])*(b[j]-b[i]) );    
121             }
122         }
123         printf("%.2lf\n",kruskal());
124     }
125     return 0;
126 }

 

posted @ 2012-09-05 19:52  pc....  阅读(210)  评论(0)    收藏  举报