标签:
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 8797 Accepted Submission(s): 4476
#include <stdio.h> #include <iostream> #include <string.h> #include <algorithm> #include <math.h> using namespace std; const int N = 105; struct Point { double x,y; }p[N]; struct Edge{ int s,e; double len; }edge[N*(N-1)/2]; int father[N],n; double dis(Point a,Point b){ return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y)); } int _find(int x){ if(x==father[x]) return x; return _find(father[x]); } int cmp(Edge a,Edge b){ return a.len<b.len; } double kruskal(int m){ sort(edge+1,edge+m+1,cmp); double cost=0; for(int i=1;i<=m;i++){ int x = _find(edge[i].s); int y = _find(edge[i].e); if(x!=y){ father[x] = y; cost +=edge[i].len; } } return cost; } int main(){ while(scanf("%d",&n)!=EOF){ for(int i=0;i<n;i++) father[i] = i; for(int i=0;i<n;i++){ scanf("%lf%lf",&p[i].x,&p[i].y); } int m =1; ///边的数量 for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ ///这里是i+1开始,从0开始会多出很多边 edge[m].s =i; edge[m].e = j; edge[m++].len = dis(p[i],p[j]); } } m--; ///记得 printf("%.2lf\n",kruskal(m)); } }
标签:
原文地址:http://www.cnblogs.com/liyinggang/p/5469166.html