记得在哪里做过一遍,最简单的最小生成树,直接用kruskal秒掉了。
代码如下:
1 #include <iostream> 2 #include <cstdio> 3 #include <cmath> 4 #include <cstring> 5 #include <cstdlib> 6 #include <algorithm> 7 #define LEN 110 8 using namespace std; 9 10 typedef struct { 11 double x, y; 12 }POINT; 13 14 POINT Point[LEN]; 15 16 typedef struct { 17 int a, b; 18 double w; 19 }ARC; 20 21 ARC Arc[LEN*LEN]; 22 int top, n; 23 24 inline double dis(POINT a, POINT b){ 25 return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y)); 26 } 27 28 //UFSet 29 int parent[LEN]; 30 31 void init(){ 32 for(int i=0; i<LEN; i++)parent[i] = i; 33 } 34 35 int Find(int x){ 36 return parent[x]==x?x:parent[x]=Find(parent[x]); 37 } 38 39 void Union(int a, int b){ 40 int pa = Find(a), pb = Find(b); 41 if(pa!=pb) parent[pa] = pb; 42 } 43 44 //kurskal 45 bool cmp(ARC a, ARC b){ 46 return a.w<b.w; 47 } 48 49 double kurskal() 50 { 51 sort(Arc, Arc+top, cmp); 52 init(); 53 double ret = 0; 54 int cnt = 0; 55 for(int i=0; i<top; i++){ 56 if(cnt == n-1) break; 57 if(Find(Arc[i].a)!=Find(Arc[i].b)){ 58 cnt++; 59 Union(Arc[i].a, Arc[i].b); 60 ret+=Arc[i].w; 61 } 62 } 63 return ret; 64 } 65 66 int main() 67 { 68 // freopen("in.txt", "r", stdin); 69 70 int T; 71 scanf("%d", &T); 72 while(T--){ 73 scanf("%d", &n); 74 for(int i=1; i<=n; i++){ 75 scanf("%lf%lf", &Point[i].x, &Point[i].y); 76 } 77 top = 0; 78 for(int i=1; i<=n; i++){ 79 for(int j=i+1; j<=n; j++){ 80 Arc[top].a = i; 81 Arc[top].b = j; 82 Arc[top].w = dis(Point[i],Point[j]); 83 top ++; 84 } 85 } 86 double ans = kurskal(); 87 printf("%.2lf ", ans); 88 if(T) printf(" "); 89 } 90 return 0; 91 }