题意:初始所有人都不是朋友,然后经过m轮把他们其中两人变为朋友,问任意选4个人这4人均为不是朋友的种数。
分析:需要我们做的是考虑合并后减少的。
我们可以想一想合并后减少的就等于合并的两个的集合内的个数相乘*其余的任选两个。即本来没合并时可以符合条件的。
#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;
}