Codeforces Round#250 D. The Child and Zoo(并差集)

时间:2022-05-19 15:24:59

题目链接:http://codeforces.com/problemset/problem/437/D

思路:并差集应用,先对所有的边从大到小排序,然后枚举边的时候,如果某条边的两个顶点不在同一个集合中就合并,并且用一个sum记录这两个集合的大小,这样这两个集合中的每一对点都要经过这条边,然后更新一下sum就可以了。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#define REP(i, a, b) for (int i = (a); i < (b); ++i)
#define FOR(i, a, b) for (int i = (a); i <= (b); ++i)
using namespace std; const int MAX_N = (100000 + 100); struct Edge {
int u, v, w;
} edge[MAX_N << 1]; int cmp(const Edge &p, const Edge &q)
{
return p.w > q.w;
}
int N, M, a[MAX_N], parent[MAX_N];
long long sum[MAX_N], ans; int Find(int x)
{
if (x == parent[x]) return x;
return parent[x] = Find(parent[x]);
} int main()
{
cin >> N >> M;
FOR(i, 1, N) cin >> a[i], parent[i] = i, sum[i] = 1;
FOR(i, 1, M) {
int u, v; cin >> u >> v;
edge[i].u = u, edge[i].v = v, edge[i].w = min(a[u], a[v]);
}
sort(edge + 1, edge + M + 1, cmp);
ans = 0;
FOR(i, 1, M) {
int r1 = Find(edge[i].u), r2 = Find(edge[i].v);
if (r1 == r2) continue;
parent[r1] = r2;
ans += edge[i].w * sum[r1] * sum[r2];
sum[r2] += sum[r1];
}
printf("%.7f\n", 2.0 * ans / (1.0 * N * (N - 1)));
return 0;
}