Boring---并查集、基础简单路径

任意门
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;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值