#include <stdio.h> #include <stdlib.h> #include <math.h> #define MAXN 100 #define MAXM 9900 int N, M; struct Edge { int u,v; double weight; } edge[MAXM]; int vertexs[MAXN]; int parents[MAXN]; double xs[MAXN]; double ys[MAXN]; int edge_cmp(const void* a, const void* b) { return (((struct Edge*)a)->weight - ((struct Edge*)b)->weight > 0) ? 1:-1; } int parents_find(int x) { int s; for(s = x; parents[s] >= 0; s = parents[s]){ ; } return s; } void parents_union(int r1, int r2) { int s1, s2; int tmp; s1 = parents_find(r1); s2 = parents_find(r2); tmp = parents[s1] + parents[s2]; if(parents[s1] < parents[s2]) { parents[s2] = s1; parents[s1] = tmp; } else { parents[s1] = s2; parents[s2] = tmp; } } void kruskal(int count) { double sum_weight = 0; int num = 0; int i, u, v; for(i = 0; i < M; i++) { u = edge[i].u; v = edge[i].v; if(parents_find(u) != parents_find(v)) { num ++; sum_weight += edge[i].weight; parents_union(parents_find(u), parents_find(v)); } if(num == N - 1) { break; } } printf("Case #%d: ", count); printf("The minimal distance is: %.2lf ", sum_weight); } int main() { int i, j; int index; double weight; int count = 1; int flag = 1; while(1) { scanf("%d", &N); if(N == 0) { break; } if(flag == 0) { printf(" "); } flag = 0; /* init */ for(i = 0; i < N; i++) { vertexs[i] = i; parents[i] = -1; } for(i = 0; i < N; i++) { scanf("%lf%lf", &xs[i], &ys[i]); } index = 0; for(i = 0; i < N; i++) { for(j = i + 1; j < N; j++) { weight = sqrt((xs[i] - xs[j])*(xs[i] - xs[j]) + (ys[i] - ys[j])*(ys[i] - ys[j])); edge[index].u = i; edge[index].v = j; edge[index].weight = weight; index ++; } } M = index; /* sort */ qsort(edge, M, sizeof(edge[0]), edge_cmp); kruskal(count); count ++; } return 0; }
有kruskal改的,格式很重要