跳到正文

题解

题解:P15439 [蓝桥杯 2025 国 Python B] 连通块

majingxuan123约 5 分钟
原文
文章信息与版本

文章信息

发布
2026年2月27日
收录
2026年2月27日
更新
2026年11月10日
篇幅
约 5 分钟
获赞
5
题目
P15439

版本

  1. v2当前
  2. v1

题目传送门

并查集:连通块?这个我擅长。
然而这道题用不了并查集。

我们记 cuta,bcut_{a,b} 代表 a,ba,b 之间的边是否被切断。

考虑从小到大枚举 xx,那么 xx 显然在 xx 的连通块里;cutx,y=0cut_{x,y}=0 的所有 yy 也在 xx 的连通块里;在所有满足条件的 yy 中,如果 cuty,z=0cut_{y,z}=0,那么 zz 也在 xx 的连通块里……

不难发现,一个非 xx 的数 zz 在 xx 的连通块里,当且仅当存在在 xx 的联通块里的一个数 yy,满足 y≠z,cuty,z=0y\ne z,cut_{y,z}=0。

于是我们观察算法标签可得,这个状物很符合 BFS 的方式,其实从省略号前面那句话也能看出来。

于是考虑从小到大枚举 xx,以 xx 为起点 BFS,扩展条件为 cutx,y=0cut_{x,y}=0,然后你就会得到如下代码。

C++
#include<bits/stdc++.h>
using namespace std;
const int N=2e5+10;
map<int,bool> cut[N];
int n,m;
int q[N],hh,tt; 
bool vis[N];
vector<int> ans[N];
int main(){
	cin>>n>>m;
	while(m--){
		int a,b;
		cin>>a>>b;
		cut[a][b]=true;
		cut[b][a]=true;
	}
	int k=0;
	for(int x=1;x<=n;x++){
		if(vis[x])continue;
		vis[x]=true; 
		hh=0,tt=-1;
		q[++tt]=x;
		while(hh<=tt){
			int x=q[hh++];
			for(int y=1;y<=n;y++)
				if(!cut[x].count(y)&&!vis[y]){
					vis[y]=true;
					q[++tt]=y;
				}
		}
		ans[++k].push_back(tt+1);
		sort(q,q+tt+1);
		for(int i=0;i<=tt;i++)ans[k].push_back(q[i]);
	}
	cout<<k<<'\n';
	for(int i=1;i<=k;i++){
		for(int x:ans[i])cout<<x<<' ';
		cout<<'\n';
	}
	return 0;
} 

这个代码会获得 7070 分,为什么呢?原因就是 BFS 时会经过大量的重复的点,使时间复杂度退化为 O(n2log⁡n)O(n^2\log n)。

从 11 到 nn 枚举实在是太不优美了,我们能不能想个方法,使其不遍历到已经属于某个连通块的点呢?

显然是有的,比如链表!

于是,我们再维护一个当前不属于任何一个连通块的点的链表,即可保证不遍历到已经属于某个连通块的点。

C++
#include<bits/stdc++.h>
using namespace std;
const int N=2e5+10;
map<int,bool> cut[N];
int n,m;
int pre[N],nxt[N];
int q[N],hh,tt; 
bool vis[N];
void remove(int x){
	pre[nxt[x]]=pre[x],nxt[pre[x]]=nxt[x],vis[x]=true;
}
vector<int> ans[N];
int main(){
	cin>>n>>m;
	nxt[0]=1,pre[n+1]=n;
	for(int i=1;i<=n;i++)pre[i]=i-1,nxt[i]=i+1;
	while(m--){
		int a,b;
		cin>>a>>b;
		cut[a][b]=true;
		cut[b][a]=true;
	}
	int k=0;
	for(int x=1;x<=n;x++){
		if(vis[x])continue;
		remove(x); 
		hh=0,tt=-1;
		q[++tt]=x;
		while(hh<=tt){
			int x=q[hh++];
			for(int y=nxt[0];y<=n;y=nxt[y])
				if(!cut[x].count(y)){
					remove(y);
					q[++tt]=y;
				}
		}
		ans[++k].push_back(tt+1);
		sort(q,q+tt+1);
		for(int i=0;i<=tt;i++)ans[k].push_back(q[i]);
	}
	cout<<k<<'\n';
	for(int i=1;i<=k;i++){
		for(int x:ans[i])cout<<x<<' ';
		cout<<'\n';
	}
	return 0;
} 

有人要问了,那你这个代码不还是会遍历到多余的点吗?

还真是,但是注意到 cuta,b=1cut_{a,b}=1 的数量只有 mm 个,所以并不影响时间复杂度。

时间复杂度:O(nlog⁡n)O(n\log n)。

注:由于 n,mn,m 的规模相同,所以写时间复杂度的时候就把 mm 当 nn 看了。

并查集:怎么没用上我!!!
于是并查集一怒之下怒了一下……
其实 this problem 就使用了并查集实现链表的方法。
我们的并查集终于有用武之地了哈哈哈。

原文
存档评论2 条抓取于