CF986C AND Graph(按位+图论)

给定一个大小为m的集合,每一个数都是0 ~ 2 n 1 的,如果两个数x,y满足x&y==0就连一条无向边,问这m个数连成的图有多少个连通块。

考虑x&y==0,那么x一定是~y的子集。于是枚举并查集维护连通性即可。
然而复杂度很要命,需要你剪枝qaq,比如说预处理一个i及i的子集是否存在,如果已经联通就不再往下做等等
复杂度 O ( n 2 n )

#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define inf 0x3f3f3f3f
#define N 4200000
inline char gc(){
    static char buf[1<<16],*S,*T;
    if(S==T){T=(S=buf)+fread(buf,1,1<<16,stdin);if(T==S) return EOF;}
    return *S++;
}
inline int read(){
    int x=0,f=1;char ch=gc();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=gc();}
    while(ch>='0'&&ch<='9') x=x*10+ch-'0',ch=gc();
    return x*f;
}
int n,m,bin[30],ans=0,a[N],fa[N];
bool vis[N],f[N];//f[i]--i及i的子集是否存在
inline int find(int x){return x==fa[x]?x:fa[x]=find(fa[x]);}
inline void merge(int x,int y){
    int xx=find(x),yy=find(y);
    if(xx!=yy) fa[xx]=yy;
}
void dfs(int x,int y){
    if(!f[x]) return;
    if(find(x)==find(y)) return;
    merge(x,y);
    for(int i=0;i<n;++i)
        if(x&bin[i]) dfs(x^bin[i],y);
}
int main(){
//  freopen("a.in","r",stdin);
    n=read();m=read();bin[0]=1;
    for(int i=1;i<=n;++i) bin[i]=bin[i-1]<<1;
    for(int i=1;i<=m;++i) a[i]=read(),f[a[i]]=1;
    for(int i=0;i<bin[n];++i){
        fa[i]=i;
        for(int j=0;j<n;++j)
            if(i&bin[j]) f[i]|=f[i^bin[j]];
    }
    for(int i=1;i<=m;++i) dfs(bin[n]-1^a[i],a[i]);
    for(int i=1;i<=m;++i) ans+=find(a[i])==a[i];
    printf("%d\n",ans);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/icefox_zhx/article/details/80521162