专题四 · 1002
Posted suamfadmp
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了专题四 · 1002相关的知识,希望对你有一定的参考价值。
代码及解释
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <iostream>
// kruskal 求最小生成树,用到并查集
struct Node
int x, y;
double cost;
g[5005];
int pre[105];
int find(int n) return n == pre[n] ? n : find(pre[n]);
bool cmp(Node a, Node b) return a.cost < b.cost;
int main()
int n;
while (scanf("%d", &n) != EOF)
int k = 0;
double sum = 0;
double x[105], y[105];
for (int i = 1; i <= n; i++)
scanf("%lf%lf", &x[i], &y[i]);
for (int i = 1; i <= n; i++)
for (int j = i + 1; j <= n; j++)
g[k].x = i;
g[k].y = j;
g[k++].cost = sqrt(fabs((x[i] - x[j]) * (x[i] - x[j]) +
(y[i] - y[j]) * (y[i] - y[j])));
for (int i = 1; i <= n; i++)
pre[i] = i;
std::sort(g, g + k, cmp);
for (int i = 0; i < k; i++)
int x = find(g[i].x);
int y = find(g[i].y);
double z = g[i].cost;
if (x != y)
sum += z;
pre[x] = y;
printf("%.2f\\n", sum);
return 0;
以上是关于专题四 · 1002的主要内容,如果未能解决你的问题,请参考以下文章