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