[POI2007]办公楼biu 并查集+dfs

Description
给你一张完全图,删去其中若干条边,问剩下的连通块数,并输出每个联通块有多少个节点。


Sample Input
7 16
1 3
1 4
1 5
2 3
3 4
4 5
4 7
4 6
5 6
6 7
2 4
2 7
2 5
3 5
3 7
1 7


Sample Output
3
1 2 4


首先题意可以变成上面那样。
然后你就考虑dfs求连通块个数。
但这里的边太多,我们于是可以考虑优化一下dfs的过程。
每访问完一个点,我们可以删掉他,因为有关他的信息已经处理过了。
这样每个点最多只会访问一次,时间复杂度应该是O(n+m)


#include <vector>
#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;
typedef long long LL;
int _min(int x, int y) {return x < y ? x : y;}
int _max(int x, int y) {return x > y ? x : y;}
int read() {
	int s = 0, f = 1; char ch = getchar();
	while(ch < '0' || ch > '9') {if(ch == '-') f = -1; ch = getchar();}
	while(ch >= '0' && ch <= '9') s = s * 10 + ch - '0', ch = getchar();
	return s * f;
}

vector<int> q[110000];
int n, cnt, fa[110000], o[110000], ans[110000];
bool v[110000];

int findfa(int x) {
	if(fa[x] != x) fa[x] = findfa(fa[x]);
	return fa[x];
}

void dfs(int x) {
	v[x] = 1;
	ans[cnt]++;
	fa[x] = x + 1;
	int tp = 0;
	for(int y = findfa(1); y <= n; y = findfa(y + 1)) {
		while(tp < q[x].size() && q[x][tp] < y) tp++;
		if(tp < q[x].size() && q[x][tp] == y) continue;
		dfs(y);
	}
}

int main() {
	n = read(); int m = read();
	for(int i = 1; i <= m; i++) {
		int x = read(), y = read();
		q[x].push_back(y), q[y].push_back(x);
	} for(int i = 1; i <= n; i++) sort(q[i].begin(), q[i].end());
	for(int i = 1; i <= n + 1; i++) fa[i] = i;
	for(int i = 1; i <= n; i++) if(!v[i]){
		cnt++, dfs(i);
	} printf("%d\n", cnt);
	sort(ans + 1, ans + cnt + 1);
	for(int i = 1; i <= cnt; i++) printf("%d ", ans[i]);
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值