题目链接
思路
$$ 有环图减小边成树的代价 <=> 总边权-最大生成树 $$
时间复杂度
$$ O((M)log(M)) $$
代码
#include <cstdio>
#include <algorithm>
#include <vector>
#include <cmath>
using namespace std;
class DSU {
public:
vector<int> p, r;
void init(int n) {
p.resize(n + 10);
r.resize(n + 10);
for (int i = 0; i <= n; i++) {
p[i] = i;
r[i] = 0;
}
}
int find(int x) {
if (x == p[x]) {
return x;
} else {
return p[x] = find(p[x]);
}
}
bool unite(int x, int y) {
x = find(x);
y = find(y);
if (x == y) {
return false;
}
if (r[x] < r[y]) {
p[x] = y;
} else {
p[y] = x;
if (r[x] == r[y]) {
r[x]++;
}
}
return true;
}
bool same(int x, int y) {
return find(x) == find(y);
}
};
DSU dsu;
const int MAXN = 1e5 + 10;
int a[MAXN], b[MAXN], id[MAXN];
double x[MAXN], y[MAXN];
double c[MAXN];
double dist(int u, int v) {
return sqrt((x[u] - x[v]) * (x[u] - x[v])
+ (y[u] - y[v]) * (y[u] - y[v]));
}
bool cmp(int u, int v) {
return c[u] > c[v];
}
int main() {
int n, m;
scanf("%d%d", &n, &m);// don't forget &
dsu.init(n);
for (int i = 1; i <= n; i++) {
scanf("%lf%lf", &x[i], &y[i]);
}
double ans = 0;
for (int i = 1; i <= m; i++) {
id[i] = i;
scanf("%d%d", &a[i], &b[i]);
c[i] = dist(a[i], b[i]);
ans += c[i];
}
sort(id + 1, id + 1 + m, cmp);
for (int i = 1; i <= m; i++) {
int u = id[i];
if (!dsu.same(a[u], b[u])) {
dsu.unite(a[u], b[u]);
ans -= c[u];
}
}
printf("%f", ans);
return 0;
}