1. 程式人生 > >[POI2007]辦公樓biu 並查集+dfs

[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;
}