http://acm.hdu.edu.cn/showproblem.php?pid=1162
Eddy's picture
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 12106 Accepted Submission(s): 6080
Problem Description
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?
Input
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.
Output
Your program prints a single real number to two decimal places: the minimum total length of ink lines that can connect all the points.
Sample Input
3
1.0 1.0
2.0 2.0
2.0 4.0
Sample Output
3.41
Author
eddy
Recommend
JGShining | We have carefully selected several similar problems for you: 1301 1102 1217 1142 1272
思路
裸的最小生成树,模板题。
与这道题极为相似:HDU 1285 畅通工程再续
AC Code
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int nmax=110;
const int mmax=10010;
int n,m;//点数、边数
struct Edge{
int u,v;//起点、终点、
double val;//边权
}edge[mmax];
bool cmp(Edge a,Edge b){
return a.val<b.val; //按照边权从小到大排序,求最小生成树
}
struct Point{
double x,y;//小岛的坐标
}p[nmax];
double getDist(int i,int j){//得到两个小岛间的距离
return sqrt((p[i].x-p[j].x)*(p[i].x-p[j].x)+(p[i].y-p[j].y)*(p[i].y-p[j].y));
}
int father[nmax];
int findFather(int u){
if(u==father[u]) return u;
else{
int f=findFather(father[u]);
father[u]=f;
return f;
}
}
void init(int n){
for(int i=0;i<n;++i){
father[i]=i;
}
}
void Kruskal(){//返回最小生成树的边权和
//init(n);
sort(edge,edge+m,cmp);
int cnt=0;//有效合并次数
double ans=0;//最小边权和
for(int i=0;i<m;i++){//遍历m条边
int fu=findFather(edge[i].u);
int fv=findFather(edge[i].v);
if(fu!=fv){
father[fu]=fv;
ans+=edge[i].val;
cnt++;
if(cnt==n-1)//合并了N-1条边,已经找到了最小生成树
break;
}
}
if(cnt==n-1)//找到最小生成树
printf("%.2lf\n",ans);
else //图不连通
return;
}
int main(int argc, char** argv) {
while(scanf("%d",&n)!=EOF){
memset(father,0,sizeof(father));
init(n);
for(int i=0;i<n;i++){
scanf("%lf %lf",&p[i].x,&p[i].y);
}
int id=0;//有id条边
for(int i=0;i<n-1;++i){
for(int j=i+1;j<n;++j){
double len=getDist(i,j);
//printf("Dist:%.5lf\n",len);
edge[id].u=i;edge[id].v=j;edge[id].val=len;
id++;
}
}
m=id;
Kruskal();
}
return 0;
}