题目大意:输入一个整数n表示表示有n个点。在接下来的n行中,每行有两个整数x , y 。分别表示一个点的横坐标以及纵坐标。求距离最小的连线
解题思路:
1)二维----->>一维
for(i = 1 ; i <= n ; ++i){
scanf("%lf%lf",&point[i].x,&point[i].y);
point[i].id = i;
}
2)求所有连线的长度
int count = 0;
for(i = 1 ; i <= n ; ++i){
for(j = i+1 ; j <= n ; ++j){
e[count].begin = point[i].id;
e[count].end = point[j].id;
e[count].weight = getDistance(point[i],point[j]);
count++;
}
}
因为之前写过一篇博客已对这种题有较详细的解释,所以这里就不详细解释了
代码如下:
/*
* 1162_1.cpp
*
* Created on: 2013年8月27日
* Author: Administrator
*/
#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;
struct edge{
int begin;
int end;
double weight;
};
const int maxn = 600;
int father[maxn];
edge e[maxn*maxn];
int find(int x){
if( x == father[x]){
return x;
}
father[x] = find(father[x]);
return father[x];
}
double kruscal(int count){
int i;
double sum = 0;
for(i = 1 ; i < maxn ; ++i){
father[i] = i;
}
for(i = 0 ; i < count ; ++i){
int fx = find(e[i].begin);
int fy = find(e[i].end);
if(fx != fy){
father[fx] = fy;
sum += e[i].weight;
}
}
return sum;
}
bool compare(const edge& a , const edge& b){
return a.weight < b.weight;
}
struct Point{
double x;
double y;
int id;
};
Point point[maxn];
double getDistance(const Point& p1 , const Point& p2){
return sqrt((p1.x - p2.x)*(p1.x - p2.x) + (p1.y - p2.y)*(p1.y - p2.y) );
}
int main(){
int n;
while(scanf("%d",&n)!=EOF){
int i,j;
for(i = 1 ; i <= n ; ++i){
scanf("%lf%lf",&point[i].x,&point[i].y);
point[i].id = i;
}
int count = 0;
for(i = 1 ; i <= n ; ++i){
for(j = i+1 ; j <= n ; ++j){
e[count].begin = point[i].id;
e[count].end = point[j].id;
e[count].weight = getDistance(point[i],point[j]);
count++;
}
}
sort(e , e + count , compare);
double sum = kruscal(count);
printf("%.2lf\n",sum);
}
}