您的位置:首页 > 其它

hdu 1162(最小生成树)

2016-05-07 20:55 204 查看

Eddy's picture

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 8797 Accepted Submission(s): 4476


[align=left]Problem Description[/align]
Eddy
begins to like painting pictures recently ,he is sure of himself to
become a painter.Every day Eddy draws pictures in his small room, and
he usually puts out his newest pictures to let his friends appreciate.
but the result it can be imagined, the friends are not interested in his
picture.Eddy feels very puzzled,in order to change all friends 's view
to his technical of painting pictures ,so Eddy creates a problem for
the his friends of you.
Problem descriptions as follows: Given you
some coordinates pionts on a drawing paper, every point links with the
ink with the straight line, causes all points finally to link in the
same place. How many distants does your duty discover the shortest
length which the ink draws?

[align=left]Input[/align]
The
first line contains 0 < n <= 100, the number of point. For each
point, a line follows; each following line contains two real numbers
indicating the (x,y) coordinates of the point.

Input contains multiple test cases. Process to the end of file.

[align=left]Output[/align]
Your
program prints a single real number to two decimal places: the minimum
total length of ink lines that can connect all the points.

[align=left]Sample Input[/align]

3
1.0 1.0
2.0 2.0
2.0 4.0

[align=left]Sample Output[/align]

3.41
题意:大意就是给你n个点求出这n个点形成的最小生成树。
题解:kruskal算法解。。开始的时候将边初始化成了0,WA了两次..好久没打过生疏了。

#include <stdio.h>
#include <iostream>
#include <string.h>
#include <algorithm>
#include <math.h>
using namespace std;

const int N = 105;
struct Point {
double x,y;
}p
;
struct Edge{
int s,e;
double len;
}edge[N*(N-1)/2];
int father
,n;
double dis(Point a,Point b){
return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
}
int _find(int x){
if(x==father[x]) return x;
return _find(father[x]);
}
int cmp(Edge a,Edge b){
return a.len<b.len;
}
double kruskal(int m){
sort(edge+1,edge+m+1,cmp);
double cost=0;
for(int i=1;i<=m;i++){
int x = _find(edge[i].s);
int y = _find(edge[i].e);
if(x!=y){
father[x] = y;
cost +=edge[i].len;
}
}
return cost;
}
int main(){
while(scanf("%d",&n)!=EOF){
for(int i=0;i<n;i++) father[i] = i;
for(int i=0;i<n;i++){
scanf("%lf%lf",&p[i].x,&p[i].y);
}
int m =1; ///边的数量
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){ ///这里是i+1开始,从0开始会多出很多边
edge[m].s =i;
edge[m].e = j;
edge[m++].len = dis(p[i],p[j]);
}
}
m--; ///记得
printf("%.2lf\n",kruskal(m));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: