All men are brothers(并查集)

题意:初始所有人都不是朋友,然后经过m轮把他们其中两人变为朋友,问任意选4个人这4人均为不是朋友的种数。

分析:需要我们做的是考虑合并后减少的。

我们可以想一想合并后减少的就等于合并的两个的集合内的个数相乘*其余的任选两个。C_{N}^{1}*C_{M}^{1}*C_{O}^{2}即本来没合并时可以符合条件的。

#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int maxn = 200010;
 
ll n, m, fa[maxn], num[maxn], re[maxn][10];
void init()
{
    for(int i = 0; i <= n; i++) fa[i] = i,num[i] = 1, re[i][0] = 1;;
    for(int i = 1; i <= n; i++)
        for(int j = 1; j <= i && j <= 4; j++)
        re[i][j] = re[i - 1][j] + re[i - 1][j - 1];
}
int find(int x)
{
    if(x == fa[x]) return x;
    return fa[x] = find(fa[x]);
}
 
int main()
{
    scanf("%lld%lld", &n, &m);
    init();
    ll sum1 = re[n][4];
    ll sum2 = re[n][2];
    printf("%lld\n", sum1);
    for(int i = 0; i < m; i++)
    {
        ll x, y;
        scanf("%lld%lld", &x, &y);
        int fx = find(x), fy = find(y);
        if(fx != fy)
        {
            ll x2 = sum2 - num[fx] * num[fy]
                - (num[fx] + num[fy]) * (n - num[fx] - num[fy]);
 
            sum1 -= x2 * num[fx] * num[fy];
            sum2 -= num[fx] * num[fy];
            if(fx < fy) swap(fx, fy);
            fa[fx] = fy, num[fy] += num[fx];
        }
        printf("%lld\n", sum1);
    }
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值