# 描述

http://www.lydsy.com/JudgeOnline/problem.php?id=1626

# 分析

Prim的证明:

Kruskal的证明:

 1 #include <bits/stdc++.h>
2 using namespace std;
3
4 const int maxn=1000+5;
5 struct pt{
6     double x,y;
7     pt(double x=0,double y=0):x(x),y(y){}
8 }p[maxn];
9 struct edge{
10     int from,to;
11     double d;
12     edge(){}
13     edge(int from,int to,double d):from(from),to(to),d(d){}
14     bool operator < (const edge &rhs) const { return d<rhs.d; }
15 }g[maxn*maxn];
16 int n,m,cnt=1;
17 int f[maxn];
18 double ans;
19 inline double dis(pt a,pt b){ return sqrt(pow(a.x-b.x,2)+pow(a.y-b.y,2)); }
20 inline int find(int x){ return x==f[x]?x:f[x]=find(f[x]); }
21 int main(){
22     scanf("%d%d",&n,&m);
23     for(int i=1;i<=n;i++){
24         scanf("%lf%lf",&p[i].x,&p[i].y);
25         f[i]=i;
26     }
27     for(int i=1;i<=m;i++){
28         int u,v; scanf("%d%d",&u,&v);
29         int fu=find(u),fv=find(v);
30         if(fu!=fv) f[fu]=fv,cnt++;
31     }
32     for(int i=1;i<=n;i++)for(int j=1;j<=n;j++) g[(i-1)*n+j]=edge(i,j,dis(p[i],p[j]));
33     sort(g+1,g+1+n*n);
34     int tot=n*n;
35     for(int i=1;i<=tot,cnt<=n;i++){
36         int fx=find(g[i].from),fy=find(g[i].to);
37         if(fx!=fy){
38             f[fx]=fy;
39             ans+=dis(p[g[i].from],p[g[i].to]);
40             cnt++;
41         }
42     }
43     printf("%.2lf\n",ans);
44     return 0;
45 }
View Code

posted @ 2016-06-13 17:39  晴歌。  阅读(131)  评论(0编辑  收藏  举报