HDU4496(并查集)

来源:互联网 发布:网络直播平台排行榜 编辑:程序博客网 时间:2024/06/15 01:20

题目大意:给一个N个顶点,M条边的无向完全图,每次删边之后输出剩余连通块的数量。

思路:并查集

一般是用并查集加边的,这题可以想象成删掉1条边,相当于增加M-1条边,然后离线操作,将答案储存起来一并输出。

#include <cstdio>#include <algorithm>#include <cmath>#include <cstring>#include <string>#include <iostream>using namespace std;const int maxn = 111111;int fa[maxn];int ans[maxn];int from[maxn], to[maxn];int n, m;void init(){    for(int i=0; i<n; i++)    {        fa[i] = i;    }}int find_fa(int x){    return fa[x] == x ? fa[x] : fa[x] = find_fa(fa[x]);}int main(){    while(scanf("%d%d", &n, &m) != EOF)    {        init();        for(int i=0; i<m; i++)        {            scanf("%d%d", &from[i], &to[i]);        }        int sum = n;        for(int i=m-1; i>=0; i--)        {            ans[i] = sum;            int fx = find_fa(from[i]);            int fy = find_fa(to[i]);            if(fx != fy)            {                sum--;                fa[fx] = fy;            }        }        for(int i=0; i<m; i++)        {            printf("%d\n", ans[i]);        }    }    return 0;}


0 0
原创粉丝点击