求最小生成树
1 //Accepted 240 KB 0 ms
2 #include <cstdio>
3 #include <cstring>
4 #include <cmath>
5 const int MAXN =105;
6 const int inf = 100000000;
7 double x[MAXN],y[MAXN];
8 double a[MAXN][MAXN];
9 bool vis[MAXN];
10 double dis[MAXN];
11 int n;
12 void pre()
13 {
14 for (int i=0;i<n;i++)
15 {
16 for (int j=0;j<n;j++)
17 {
18 a[i][j]=sqrt((double )(x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j]));
19 }
20 }
21 }
22 double prim()
23 {
24 double ans=0;
25 memset(vis,0,sizeof(vis));
26 for (int i=0;i<n;i++)
27 dis[i]=(double )inf;
28 dis[0]=0;
29 for (int i=0;i<n;i++)
30 {
31 double temp=(double )inf;
32 int k=0;
33 for (int j=0;j<n;j++)
34 {
35 if (vis[j]) continue;
36 if (temp>dis[j])
37 {
38 temp=dis[j];
39 k=j;
40 }
41 }
42 vis[k]=1;
43 ans+=temp;
44 for (int j=0;j<n;j++)
45 {
46 if (vis[j]) continue;
47 if (dis[j]>a[k][j])
48 {
49 dis[j]=a[k][j];
50 }
51 }
52 }
53 return ans;
54 }
55 int main()
56 {
57 while (scanf("%d",&n)!=EOF)
58 {
59 for (int i=0;i<n;i++)
60 {
61 scanf("%lf%lf",&x[i],&y[i]);
62 }
63 pre();
64 double ans=prim();
65 printf("%.2f\n",ans);
66 }
67 return 0;
68 }
poj2560
时间: 2024-10-09 05:57:31