您的位置:首页 > 其它

POJ2560_Freckles_最小生成树

2013-07-09 17:01 267 查看
- -刚开始我看输入把我下了一跳,平面上n个点怎么遍历啊。后来才发现自己二到忘记看规模了,n<100,直接枚举就可以啊

......

然后就是裸的最小生成树的Kruskal算法

悲催的是自己连这个都没有一遍过

对自己的水平无语了

- -好了吐槽结束

Kruskal算法非常的经典,而且形式也比较固定,所以就懒得写注释了

不过需要提醒的是sort函数,我又忘了cmp如何定义是升序还是降序了...囧

又百度了一下,记住sort默认是升序的,是按Operator<来排序的,以后不能再忘了

Freckles

Time Limit: 1000MSMemory Limit: 65536K
Total Submissions: 6029Accepted: 3042
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.
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


#include<stdio.h>
#include<string.h>
#include<math.h>
#include<algorithm>
using namespace std;
typedef struct MyStruct
{
double x,y;
}NODE;
typedef struct MyStruct2
{
int u,v;
double dis;
}EDGE;
NODE point[102];
EDGE edge[10010];
int parent[102];
double find_distance(NODE a,NODE b)
{
return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
}

int find_parent(int p)
{
if (parent[p]!=p)
{
parent[p]=find_parent(parent[p]);
}
return parent[p];
}

int find_merge(EDGE x)
{
int a=find_parent( x.u);
int b=find_parent(x.v);
if (a!=b)
{
parent[a]=b;
return 1;
}
return 0;
}
bool cmp(EDGE a,EDGE b)
{
return a.dis<b.dis;
}

int main()
{
int n,i,j,k,counter;
double ans;
while (scanf("%d",&n)!=EOF)
{
for ( i = 0; i < n; i++)
{
scanf("%lf%lf",&point[i].x,&point[i].y);
parent[i]=i;
}
k=0;
for ( i = 0; i < n; i++)
{
for ( j = i+1; j < n; j++)
{
edge[k].u=i;edge[k].v=j;
edge[k].dis=find_distance(point[i],point[j]);
k++;
}
}
sort(edge,edge+k,cmp);
ans=0;counter=0;
for ( i = 0; i < k; i++)
{
if (find_merge(edge[i]))
{
ans+=edge[i].dis;counter++;
}
if (counter==n-1)
{
break;
}
}
printf("%.2lf\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: