[HDU4496] D-City [并查集]

[ L i n k \frak{Link} ]


询问删除前 i [ 1 , m ] \frak{i\in[1,m]} 条边后图中剩下多少个连通块。
没有其他操作。显然可以简单离线。
把删除倒成添加。
并查集维护。
坑:1.点的标号从 0 \frak{0} N 1 \frak{N-1}
2.多组数据


#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<cctype>
#include<cstdlib>
using namespace std;
int n, m, tot;
int fa[10005];
int u[100005];
int v[100005];
int ans[100005];
int find(int x) {
    return fa[x] == x ? x : fa[x] = find(fa[x]);
}
void merge(int x, int y) {
    int fx = find(x);
    int fy = find(y);
    if (fx == fy) return;
    --tot;
    fa[fx] = fy;
}
int main() {
    while (~scanf("%d%d", &n, &m)) {
   		tot = n;
    	for (int i = 0; i < n; ++i) {
        	fa[i] = i;
    	} 
    	for (int i = 1; i <= m; ++i) {
    	    scanf("%d%d", &u[i], &v[i]);
    	}
    	for (int i = m; i > 1; --i) {
    	    merge(u[i], v[i]);
    	    ans[i] = tot;
    	}
    	for (int i = 2; i <= m; ++i) {
    	    printf("%d\n", ans[i]);
    	}
    	printf("%d\n", n);
	}
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Estia_/article/details/83818956