我是靠谱客的博主 腼腆帅哥,最近开发中收集的这篇文章主要介绍Educational Codeforces Round 37 E. Connected Components?(bfs+思路),觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

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 m (1 ≤ n ≤ 200000).

Then m lines follow, each containing a pair of integers x and y (1 ≤ x, y ≤ nx ≠ 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[N];
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("%dn",ans.size());
for(int i=0;i<ans.size();i++)
printf("%d ",ans[i]);
puts("");
}


最后

以上就是腼腆帅哥为你收集整理的Educational Codeforces Round 37 E. Connected Components?(bfs+思路)的全部内容,希望文章能够帮你解决Educational Codeforces Round 37 E. Connected Components?(bfs+思路)所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(33)

评论列表共有 0 条评论

立即
投稿
返回
顶部