题目描述
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.
示例1
输入
3
1.0 1.0
2.0 2.0
2.0 4.0
输出
3.41
思路
本题和“还是畅通工程”的区别在于,本题是输入所有的点的坐标,而不是所有的无向边。
所以将所有的点进行连线,然后用并查集进行克鲁斯卡尔算法的计算即可。
需要注意的是,在map中要利用自己定义的结构体作为关键字,必须要进行“<”字符的重载。
代码
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<map>
using namespace std;
const int MAXN=100;
struct Point{
double x;
double y;
int priority;
bool operator!=(const Point& p) const{
return x!=p.x||y!=p.y;
}
bool operator<(const Point& p) const{ //为了使map能用自定义的结构体作为关键字
return priority<p.priority;
}
};
struct Edge{
Point from;//边的起点
Point to;//边的终点
double length;//边的长度
bool operator<(const Edge& e) const{
return length<e.length;
}
};
Edge edge[MAXN*MAXN];//边集
Point point[MAXN];//点集
map<Point,Point> father;
map<Point,int> height;
void Initial(int n)
{
for(int i=0;i<=n;i++)
{
father[point[i]]=point[i];
height[point[i]]=0;
}
}
Point Find(Point p)
{
if(p!=father[p])
father[p]=Find(father[p]);
return father[p];
}
void Union(Point x,Point y)
{
x=Find(x);
y=Find(y);
if(x!=y)
{
if(height[x]<height[y])
father[x]=y;
else if(height[x]>height[y])
father[y]=x;
else{
father[y]=x;
height[x]++;
}
}
}
double Kruskal(int n,int edgeNumber)
{
Initial(n);
sort(edge,edge+edgeNumber);//按权值排序
double sum=0.0;
for(int i=0;i<edgeNumber;i++)
{
Edge current=edge[i];
if(Find(current.from)!=Find(current.to))
{
Union(current.from,current.to);
sum+=current.length;
}
}
return sum;
}
int main()
{
int n;
while(cin>>n)
{
if(n==0)
break;
int edgeNumber=n*(n-1);
for(int i=0;i<n;i++)
{
cin>>point[i].x>>point[i].y;
point[i].priority=i;
}
int m=0;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(i!=j)
{
edge[m].from=point[i];
edge[m].to=point[j];
double num=(point[i].x-point[j].x)*(point[i].x-point[j].x)
+(point[i].y-point[j].y)*(point[i].y-point[j].y);
edge[m].length=sqrt(num);
m++;
}
}
}
double answer=Kruskal(n,edgeNumber);
printf("%.2f\n",answer);
}
return 0;
}