Description
In an episode of the Dick Van Dyke show, little Richie connects the freckles on his Dad's back to form a picture of the Liberty Bell. Alas, one of the freckles turns out to be a scar, so his Ripley's engagement falls through.
Consider Dick's back to be a plane with freckles at various (x,y) locations. Your job is to tell Richie how to connect the dots so as to minimize the amount of ink used. Richie connects the dots by drawing straight lines between pairs, possibly lifting the pen between lines. When Richie is done there must be a sequence of connected lines from any freckle to any other freckle.
Consider Dick's back to be a plane with freckles at various (x,y) locations. Your job is to tell Richie how to connect the dots so as to minimize the amount of ink used. Richie connects the dots by drawing straight lines between pairs, possibly lifting the pen between lines. When Richie is done there must be a sequence of connected lines from any freckle to any other freckle.
Input
The first line contains 0 < n <= 100, the number of freckles on Dick's back. For each freckle, a line follows; each following line contains two real numbers indicating the (x,y) coordinates of the freckle.
Output
Your program prints a single real number to two decimal places: the minimum total length of ink lines that can connect all the freckles.
Sample Input
3
1.0 1.0
2.0 2.0
2.0 4.0
Sample Output
3.41
题解:
最小生成树问题,把所有点用一个数字表示然后用kruskal算法。
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<math.h> #include<algorithm> #include<iostream> using namespace std; int parent[105]; struct lu { int a,b; float length; } lu[10010]; struct point { float x,y; int num; }point[105]; int root(int p) { if(parent[p]==-1) return p; else return parent[p]=root(parent[p]); } void merge(int a,int b) { a=root(a); b=root(b); parent[a]=b; } int cmp(const void *a,const void *b) { struct lu *c,*d; c=(struct lu *)a; d=(struct lu *)b; if(c->length>d->length) return 1; if(c->length==d->length) return 0; if(c->length<d->length) return -1; } void ling() { int i,j,k; for(i=0;i<105;i++) parent[i]=-1; for(i=0;i<10010;i++) { lu[i].length=0.0; } } int main() { int i,j,k,l,m,n; float ans; while(scanf("%d",&n)!=EOF) { ling(); for(i=0;i<n;i++) { scanf("%f%f",&point[i].x,&point[i].y); } l=0; ans=0.0; for(i=0;i<n;i++) for(j=i+1;j<n;j++) { lu[l].a=i; lu[l].b=j; lu[l].length=sqrt((point[i].x-point[j].x)*(point[i].x-point[j].x)+(point[i].y-point[j].y)*(point[i].y-point[j].y)); l++; } qsort(lu,n*(n+1)/2,sizeof(struct lu),cmp); for(i=0;i<n*n;i++) { if(root(lu[i].a)!=root(lu[i].b)) { merge(lu[i].a,lu[i].b); ans=ans+lu[i].length; } } printf("%.2f\n",ans); } return 0; }