任意门
Here is a graph with N points and M undirected edges. The edge numbered i connects two points numbered Ai and Bi, and at the very beginning there is a simple path between any two points.
Let us define the inconvenience: how many pairs of points (a,b)(a<b) make it no longer possible to connect the point numbered a and the point numbered b with some remaining edges. For each i (1≤i≤M), find the inconvenience when the edge numbered i has just been deleted.
Input
Input contains M+1 lines, the first two integers for N and M (2≤N≤105,1≤M≤105), followeing M lines, each line contains two integers Ai and Bi(1≤Ai<Bi≤N).
Output
Output contains M lines, with one integer per line representing the result.
input
4 5
1 2
3 4
1 3
2 3
1 4
output
0
0
4
5
6
input
2 1
1 2
output
1
这道题目要倒着做,正着做就是我减少一条边会减少多少条简单路径,反着做,就是我们每增加一条边,会增加多少条简单路径,我们会发现每次变化的值就是(如下图所示,c1*c2),用所有总的路径减去变化的即可。
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=100010;
ll f[N], pp[N], cnt[N];
int h=0;
struct node{
int x, y;
}nd[N];
int find(int x) {
if(f[x]==x) return x;
else return f[x] = find(f[x]);//路径压缩
}
void merge(int a,int b) {
cnt[b] += cnt[a];//计算该并查集中的元素个数
f[a] = b;
}
int main() {
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
#endif
int n,m;
cin>>n>>m;
for(int i=1;i<=n;i++) cnt[i] = 1, f[i] = i;
int x, y;
for(int i=1;i<=m;i++) {
cin>>x>>y;
nd[i].x=x;
nd[i].y=y;
}
ll sum = 1ll * n * (n - 1) / 2, tot = 0;
pp[h++] = sum;
for(int k=m; k>0; k--) {
int x = nd[k].x, y = nd[k].y;
int u = find(x), v = find(y);//先找父亲节点,直接对父亲节点进行合并
ll c1 = cnt[u], c2 = cnt[v];
if(u != v) {
merge(u, v);
tot += c1 * c2;
pp[h] = sum - tot;
}
else {
pp[h] = pp[h-1];
}
h++;
}
for(int i=m-1; i>=0; i--) {
printf("%lld\n", pp[i]);
}
return 0;
}