九度 题目1144:Freckles
原题OJ链接:http://ac.jobdu.com/problem.php?pid=1144
题目描述:
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.
输入:
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.
输出:
Your program prints a single real number to two decimal places: the minimum total length of ink lines that can connect all the freckles.
样例输入:
3
1.0 1.0
2.0 2.0
2.0 4.0
样例输出:
3.41
解题思路:
题目大意为平面上有若干个点,我们需要用一些线段来将这些点连接起来使任意两个点能够通过一系列的线段相连,给出所有点的坐标,求一种连接方式使所有线段的长度和最小,求该长度和。
若将平面上的点抽象成图上的点,将结点间直接相邻的线段抽象成链接结点的边,且权值为其长度,那么类似于几何最优值的问题转化为图论上的最小生成树问题。但在开始求最小生成树之前,必须建立该图,得出所有的边和相应的权值。
源代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#define MAX_N 105
using namespace std;
int Tree[MAX_N];
struct Node{
double x,y;
} V[MAX_N];
struct Edge{
int n1,n2;
double cost;
} E[6000];
bool cmp(Edge a,Edge b){
return a.cost<b.cost;
}
int findRoot(int x){
if(Tree[x]==-1) return x;
else{
int tmp=findRoot(Tree[x]);
Tree[x]=tmp;
return tmp;
}
}
int main(){
int n;
while(cin>>n){
memset(Tree,-1,sizeof(Tree));
for(int i=0;i<n;i++){
cin>>V[i].x>>V[i].y;
}
int k=0;
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
E[k].n1=i;
E[k].n2=j;
E[k].cost=sqrt((V[i].x-V[j].x)*(V[i].x-V[j].x)+
(V[i].y-V[j].y)*(V[i].y-V[j].y));
k++;
}
}
sort(E,E+k,cmp);
double ans=0.0;
for(int i=0;i<k;i++){
int a=E[i].n1;
int b=E[i].n2;
a=findRoot(a);
b=findRoot(b);
if(a!=b){
Tree[a]=b;
ans=ans+E[i].cost;
}
}
printf("%.2f\n",ans);
}
return 0;
}