1 #include<iostream> 2 #include<algorithm> 3 #include<cmath> 4 #include<iomanip> 5 #define MAXN 105 6 #define inf 1000000000 7 using namespace std; 8 9 typedef double elem_t; 10 11 double point[MAXN][2]; 12 double _m[MAXN][MAXN]; 13 int pre[MAXN]; 14 elem_t prim(int n,elem_t mat[][MAXN],int* pre); 15 int main() 16 { 17 //freopen("acm.acm","r",stdin); 18 int num; 19 int i; 20 int j; 21 double x; 22 double y; 23 cin>>num; 24 for(i = 0; i < num; ++ i) 25 { 26 cin>>point[i][0]>>point[i][1]; 27 } 28 for(i = 0; i < num; ++ i) 29 { 30 for(j = i+1; j < num; ++ j) 31 { 32 _m[i][j] = sqrt((point[i][0] - point[j][0])*(point[i][0] - point[j][0]) + (point[i][1] - point[j][1])*(point[i][1] - point[j][1])); 33 _m[j][i] = _m[i][j]; 34 } 35 } 36 cout<<setiosflags(ios::fixed)<<setprecision(2)<<prim(num,_m,pre)<<endl; 37 } 38 39 40 elem_t prim(int n,elem_t mat[][MAXN],int* pre){ 41 elem_t min[MAXN],ret=0; 42 int v[MAXN],i,j,k; 43 for (i=0;i<n;i++) 44 min[i]=inf,v[i]=0,pre[i]=-1; 45 for (min[j=0]=0;j<n;j++){ 46 for (k=-1,i=0;i<n;i++) 47 if (!v[i]&&(k==-1||min[i]<min[k])) 48 k=i; 49 for (v[k]=1,ret+=min[k],i=0;i<n;i++) 50 if (!v[i]&&mat[k][i]<min[i]) 51 min[i]=mat[pre[i]=k][i]; 52 } 53 return ret; 54 }
时间: 2024-10-13 20:15:06