只看看数据就知道怎么回事了,花5分钟又写了遍kruscal,的确经典! #include <iostream> #include <algorithm> #include <cmath> using namespace std; struct point { double x,y; }p[110]; struct edge { int x,y; double c; }a[10010]; int n,tot,i,j,k1,k2,f[110]; double ans; int find(int i) { if (i!=f[i]) f[i]=find(f[i]); return f[i]; } double dis(point a, point b) { return pow((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y),0.5); } bool cmp(edge a,edge b) { return a.c<b.c; } int main() { tot=0; cin >> n; for (i=1;i<=n;i++) { cin >> p[i].x >> p[i].y; for (j=1;j<i;j++) { tot++; a[tot].x=i; a[tot].y=j; a[tot].c=dis(p[i],p[j]); } } sort(a+1,a+tot+1,cmp); ans=0; for (i=1;i<=n;i++) f[i]=i; for (i=1;i<=tot;i++) { k1=find(a[i].x); k2=find(a[i].y); if (k1!=k2) { f[k1]=k2; ans+=a[i].c; } } printf("%.2lf/n",ans); //system("pause"); return 0; }