您的位置:首页 > 其它

Educational Codeforces Round 37 E. Connected Components?(bfs+思路)

2018-02-03 09:56 369 查看
E. Connected Components?

time limit per test
2 seconds

memory limit per test
256 megabytes

input
standard input

output
standard output

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.

Input

The first line contains two integers n and <
ea3e
span class="tex-span" style="font-size:17.5px;font-family:'times new roman', sans-serif;white-space:nowrap;">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.

Output

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.

Example

input
5 5
1 2
3 4
3 2
4 2
2 5


output
2
1 4


题意:给出n个点,m条不存在的边(除了不存在的边其他边都存在),输出有多少个连通分量,以及每个连通分量里点的个数(从小到大)

首先是存图,2e5*2e5的图,而且边又经常用到,用邻接表肯定是不行的,二维map可以解决这个问题

然后是优化,一个连通分量中的点都在同一个集合里,由于是无向图,对于一个连通分量中的点,他们之间可能会连很多条边,但只需要一条边就能确定他们之间的关系,所以其他那么多条边都可以优化掉,利用bfs,每次把v删掉,然后看剩下所有没加入集合中的点是否与v有关系,有关系则加入一个集合里,再把这点删了,重复这个过程即可

#include<bits/stdc++.h>
#define mem(a,b) memset(a,b,sizeof(a))
using namespace std;
const int N=200005;
map<int,bool>e
;
vector<int>mp,ans;
int bfs(int v)
{
int cnt=0;
queue<int>Q;
Q.push(v);
while(!Q.empty())
{
int u=Q.front();
Q.pop();
cnt++;
for(int i=0;i<mp.size();i++)
{
v=mp[i];
if(!e[u][v])
{
swap(mp[i],mp.back());
mp.pop_back();
--i;
Q.push(v);
}
}
}
return cnt;
}

int main()
{
int n,m,x,y;
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)mp.push_back(i);
for(int i=1; i<=m; i++)
{
scanf("%d%d",&x,&y);
e[x][y]=1;
e[y][x]=1;
}
while(!mp.empty())
{
int v=mp.back();
mp.pop_back();
int x=bfs(v);
if(x)
ans.push_back(x);
}
sort(ans.begin(),ans.end());
printf("%d\n",ans.size());
for(int i=0;i<ans.size();i++)
printf("%d ",ans[i]);
puts("");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: