Problem A: Freckles
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 input begins with a single positive integer on a line by itself indicating the number of the cases following, each of them as described below. This line is followed by a blank line, and there is also a blank line between two consecutive inputs.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
For each test case, the output must follow the description below. The outputs of two consecutive cases will be separated by a blank line.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
1 3 1.0 1.0 2.0 2.0 2.0 4.0
Sample Output
3.41
题意:裸最小生成树。
AC代码如下:
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
struct node
{
int u,v;
double w;
}edge[10010];
bool cmp(node a,node b)
{
return a.w<b.w;
}
double x[110],y[110],ans;
int p[110],n,num;
int find(int x)
{
return x==p[x] ? x : p[x]=find(p[x]);
}
void Kruskal()
{
int u,v,i;
for(i=1;i<=n;i++)
p[i]=i;
for(i=1;i<=num;i++)
{
u=find(edge[i].u);
v=find(edge[i].v);
if(u!=v)
{
ans+=edge[i].w;
p[v]=u;
}
}
}
int main()
{
int T,t,i,j,k;
scanf("%d",&T);
for(t=1;t<=T;t++)
{
if(t!=1)
printf("\n");
scanf("%d",&n);
for(i=1;i<=n;i++)
scanf("%lf%lf",&x[i],&y[i]);
num=0;
for(i=1;i<=n;i++)
for(j=i+1;j<=n;j++)
{
edge[++num].u=i;
edge[num].v=j;
edge[num].w=sqrt((x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j]));
}
sort(edge+1,edge+1+num,cmp);
ans=0;
Kruskal();
printf("%.2f\n",ans);
}
}

此博客介绍了一个经典的算法问题——如何用最少的“墨水”将平面上的若干个点(模拟为人物背上的雀斑)通过直线连接起来。这是一个典型的最小生成树问题,文章提供了详细的AC代码实现。
1175

被折叠的 条评论
为什么被折叠?



