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

· · 题解

题目传送门

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

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

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

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

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

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

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

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

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

显然是有的,比如链表!

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

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

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

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

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

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

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