You are given an undirected graph consisting of n vertices and edges.
Instead of giving you the edges that exist in the graph, we give you m unordered pairs (x, y)
such that there is no edge between x and y,
and if some pair of vertices is not listed in the input, then there is an edge between these vertices.
You have to find the number of connected components in the graph and the size of each component. A connected component is a set of vertices X such that for every two vertices from this set there exists at least one path in the graph connecting these vertices, but adding any other vertex to X violates this rule.
The first line contains two integers n and m (1 ≤ n ≤ 200000, ).
Then m lines follow, each containing a pair of integers x and y (1 ≤ x, y ≤ n, x ≠ y) denoting that there is no edge between x and y. Each pair is listed at most once; (x, y) and (y, x) are considered the same (so they are never listed in the same test). If some pair of vertices is not listed in the input, then there exists an edge between those vertices.
Firstly print k — the number of connected components in this graph.
Then print k integers — the sizes of components. You should output these integers in non-descending order.
5 5 1 2 3 4 3 2 4 2 2 5
2 1 4
题意:给你一张无向图,输出它补图所有联通块的大小
解题思路:bfs即可,用一个set记录哪些点还未确定是哪个联通块(加了个记录数组就MLE,真是有毒,只能再开一个set记录能走到哪些点)
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <vector>
#include <bitset>
#include <functional>
using namespace std;
#define LL long long
const int INF = 0x3f3f3f3f;
int n, m, x, y;
vector<int>g[200001];
bool vis[200001];
int ans[200001];
set<int>ss;
queue<int>q;
int main()
{
while (~scanf("%d %d", &n, &m))
{
memset(vis, 0, sizeof vis);
int tot = 0;
for (int i = 0; i < n; i++) g[i].clear();
for (int i = 0; i < m; i++)
{
scanf("%d %d", &x, &y);
g[x].push_back(y);
g[y].push_back(x);
}
for (int i = 1; i <= n; i++) ss.insert(i);
for (int i = 1; i <= n; i++)
{
if (vis[i]) continue;
q.push(i);
ans[tot++] = 0;
while (!q.empty())
{
int pre = q.front();
q.pop();
if (vis[pre]) continue;
vis[pre] = 1;
ans[tot - 1]++;
set<int>tmp;
for (int i = 0; i < g[pre].size(); i++)
{
if (vis[g[pre][i]]) continue;
tmp.insert(g[pre][i]);
}
for (set<int>::iterator it = tmp.begin(); it != tmp.end(); it++) ss.erase(*it);
for (set<int>::iterator it = ss.begin(); it != ss.end(); it++) q.push(*it);
swap(ss, tmp);
}
}
sort(ans, ans + tot);
printf("%d\n", tot);
for (int i = 0; i < tot; i++)
{
if (i) printf(" ");
printf("%d", ans[i]);
}
printf("\n");
}
return 0;
}