利用并查集求最短路,注意浮点数,再就是需要准备一下边集。
#include<stdio.h> #include<math.h> #include<stdlib.h> #define MAXN 5000 + 100 #define MAXN1 100 + 10 int n, m, p1, p[MAXN1],r[MAXN],u[MAXN],v[MAXN]; double w[MAXN], x[MAXN1], y[MAXN1]; int cmp(const void *_p, const void *_q) { int *p = (int *)_p; int *q = (int *)_q; return w[*p] > w[*q] ? 1 : -1; } int find(int x) {return p[x] == x ? x : p[x] = find(p[x]);} void kruskal() { double ans = 0; for(int i = 0; i < m; i ++) p[i] = i; for(int i = 0; i < p1; i ++) r[i] = i; qsort(r, p1, sizeof(r[0]),cmp); for(int i = 0; i < p1; i ++) { int e = r[i]; int s = find(u[e]); int o = find(v[e]); if(s != o) { ans += w[e]; p[s] = o;} } printf("%.2lf\n",ans); } void solve() { p1 = 0; for(int i = 0; i < m; i ++) for(int j = i + 1; j < m; j ++) { w[p1] = sqrt((x[i]-x[j])*(x[i]-x[j]) + (y[i]-y[j])*(y[i]-y[j])); u[p1] = i; v[p1] = j; p1 ++; } kruskal(); } void init() { while(~scanf("%d",&n)) while(n --) { scanf("%d",&m); for(int i = 0; i < m; i ++) scanf("%lf%lf",&x[i],&y[i]); solve(); if(n) puts(""); } } int main() { init(); return 0; }