uva 10034 Freckles
Freckles
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 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
题目大意:给出N个点的坐标,要求出联通所有点的最短路径。
解题思路:最小生成树Kruskal算法。
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cstdlib>
using namespace std;
typedef long long ll;
int num[105];
int get_fa(int x) {
return num[x] != x ? get_fa(num[x]) : x;
}
struct Node{
double x, y;
}N[105];
struct W{
int a, b;
double len;
}w[10005];
int cmp(W a, W b) {
return a.len < b.len;
}
double getlen(Node a, Node b) { //计算两点间距离
return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));
}
int main() {
int T;
scanf("%d", &T);
while (T--) {
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%lf %lf", &N[i].x, &N[i].y);
num[i] = i; //初始化并查集
}
int cnt = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
w[cnt].len = getlen(N[i], N[j]);
w[cnt].a = i;
w[cnt++].b = j;
}
}
sort(w, w + cnt, cmp);
double sum = 0;
for (int i = 0; i < cnt; i++) {
if (get_fa(w[i].a) == get_fa(w[i].b)) continue;
sum += w[i].len; //如果两点在不同集合,合并
num[get_fa(w[i].a)] = get_fa(w[i].b);
}
printf("%.2lf\n", sum);
if (T) printf("\n");
}
return 0;
}