Codeforces Round #250 (Div. 2) (D. The Child and Zoo(并查集))

题目链接:点击打开链接

题意:给你一个n个点, m条边的图, 每个点有一个点权值, 我们定义f(p, q)表示p点到q点的一条路径, 要求这条路径上的最小点权尽量大, 其值等于最小点权值。  求任意一对点的f值之和除以n * (n - 1) , 即平均值。

思路: 其实转化一下, 就是要先求最大生成树, 那么路径一定在树种, 且唯一。  那么我们从大到小来, 每次将两个集合合并的时候, 那么A集合到B集合的所有路径上的最小值就是当前两个集合维护的最小值, 所以, 在每个集合中维护一下最小值, 和集合中点的个数就行了。  并查集搞之。

细节参见代码:

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include<deque>
#include<map>
#include<queue>
#define Max(a,b) ((a)>(b)?(a):(b))
#define Min(a,b) ((a)<(b)?(a):(b))
using namespace std;
typedef long long ll;
typedef long double ld;
const ld eps = 1e-9, PI = 3.1415926535897932384626433832795;
const int mod = 1000000000 + 7;
const int INF = 0x3f3f3f3f;
// & 0x7FFFFFFF
const int seed = 131;
const ll INF64 = ll(1e18);
const int maxn = 100000 + 10;
int T,n,m,p[maxn],v[maxn];
ll maxv[maxn], cnt[maxn];
struct node {
    int a, b, c;
    node(int a=0, int b=0, int c=0):a(a), b(b), c(c) {}
    bool operator < (const node& rhs) const {
        return c > rhs.c;
    }
}a[maxn];
int _find(int x) { return p[x] == x ? x : p[x] = _find(p[x]); }
double solve() {
    sort(a, a+m);
    for(int i=1;i<=n;i++) {
        p[i] = i;
        maxv[i] = v[i];
        cnt[i] = 1;
    }
    double ans = 0;
    for(int i=0;i<m;i++) {
        int x = _find(a[i].a);
        int y = _find(a[i].b);
        if(x != y) {
            p[x] = y;
            maxv[y] = min(maxv[y], maxv[x]);
            ans += 1.0 * a[i].c * cnt[x] * cnt[y];
            cnt[y] += cnt[x];
        }
    }
    return 2.0 * ans/(n*1.0 * (double)(n-1));
}
int main() {
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++) scanf("%d",&v[i]);
    for(int i=0;i<m;i++) {
        scanf("%d%d",&a[i].a,&a[i].b);
        a[i].c = min(v[a[i].a], v[a[i].b]);
    }
    printf("%.6f\n",solve());
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值