——by A Code Rabbit
Description
求直角坐标系上能够把几个点相连起来最短线段的长度。
输入每个点的坐标。
输出最短线段的长度。
Graph Algorithms
Analysis
经典的最小生成树的题目。
求最小生成树的两种算法——Kruskal 和 Prim。
设图 G 中点数为 n ,边数为 e 。
Kruskal 的时间复杂度为 O(e log e) ,取决于对边的排序效率。
要求存储每条边,可用并查集优化(由于并查集优化后代码更短,效率更高,因此默认都用并查集优化后的 Kruskal。
Prim 的时间复杂度是比较多变,取决于图的存储结构,和是否采用二叉堆(优先队列)优化。
未优化的时间复杂度为 O(n^2) ,适合于稠密图。而是堆优化过后,时间复杂度达到O(e log n),不过相比Kruskal属于费力不讨好。
除非利用 Fibonacci 堆优化,可以达到 O(n log n) 。
Fibonacci堆 优化的实现较难(反正我不懂),所以在 ACM 中,大都采用 Kruskal 的方法求最小生成树的路径长度。
// UVaOJ 10034
// Freckles
// by A Code Rabbit
#include <algorithm>
#include <cmath>
#include <cstdio>
using namespace std;
const int MAXV = 102;
const int MAXE = MAXV * MAXV;
template <typename T>
struct Point {
T x, y;
static double GetDistance(Point a, Point b) {
return sqrt(pow(a.x - b.x, 2) + pow(a.y - b.y, 2));
}
};
template <typename T>
struct Edge {
int u, v;
T w;
};
template <typename T>
struct Graph{
Edge<T> edge[MAXE];
int tot_edge;
void Init() { tot_edge = 0; }
void AddEdge(int u, int v, T w) {
edge[tot_edge].u = u;
edge[tot_edge].v = v;
edge[tot_edge].w = w;
tot_edge++;
}
};
namespace Kruskal {
int p[MAXV];
template <typename T>
int Cmp(Edge<T> a, Edge<T> b) { return a.w < b.w; }
int Find(int x) { return p[x] == x ? x : p[x] = Find(p[x]); }
template <typename T>
T Go(Edge<T> e[MAXE], int n, int m) {
for (int i = 0; i < n; i++) p[i] = i;
sort(e, e + m, Cmp<T>);
T ans = 0;
for (int i = 0; i < m; i++) {
int u = Find(e[i].u); int v = Find(e[i].v);
if (u != v) { ans += e[i].w; p[u] = v; }
}
return ans;
}
}
int n;
Point<double> point[MAXV];
Graph<double> graph;
int main() {
int tot_case;
scanf("%d", &tot_case);
for (int t = 0; t < tot_case; t++) {
// Input.
scanf("%d", &n);
for (int i = 0; i < n; i++)
scanf("%lf%lf", &point[i].x, &point[i].y);
// Compute each the length of edges.
graph.Init();
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++) {
double w = Point<double>::GetDistance(point[i], point[j]);
graph.AddEdge(i, j, w);
}
}
// Output.
printf("%s", t ? "\n" : "");
printf("%.2lf\n", Kruskal::Go(graph.edge, n, graph.tot_edge));
}
return 0;
}