You are given a set of size m with integer elements between 0 and 2n−1 inclusive. Let's build an undirected graph on these integers in the following way: connect two integers x and y with an edge if and only if x&y=0. Here & is the bitwise AND operation. Count the number of connected components in that graph.
In the first line of input there are two integers n and m (0≤n≤22, 1≤m≤2n).
In the second line there are m integers a1,a2,…,am (0≤ai<2n) — the elements of the set. All ai are distinct.
Print the number of connected components.
2 3 1 2 3
2
5 5 5 19 10 20 12
2
Graph from first sample:
Graph from second sample:
不好意思啦。。。我又被位运算题干倒了。。。这道题的精髓全在构图的时候用的那些位运算上,一共要有2*2^n个点,0-2^n-1每个点对应一个求弱连通分量时起辅助作用的数,2^n-2*2^n对应题目当中给出的数加2^n。开一个has数组,记录这个值是否有在输入中出现。然后,我们图里的边有三种,一种是从输入的值所对应的点到与其相等的我们用作辅助的点,一种是从一个辅助的点,到另一个将原点对应值二进制某一位的0变成1的辅助的点,第三种是从一个辅助的点到对其值求反后所对应的输入的点。这样就成功把每一个做与运算都会得到0的点连起来了。
空间有限,不能开记录边的数组,一并搁在dfs里跑了,在开个vis数组记录是否有访问过该点。
#include<iostream>
#include<cstdio>
#include<string.h>
#include<algorithm>
using namespace std;
int e=0,a[9000000];
bool has[9000000],vis[9000000];
int n,m;
int base;
void dfs(int u)
{
//cout<<"u="<<u<<endl;
vis[u]=true;
if (u>=base)
{
int v=u-base;
if (!vis[v]) dfs(v);
}else
{
for (int i=0; i<n; i++)
{
int tmp=(1<<i);
if (tmp&u) continue;
if (!vis[tmp|u]) dfs(tmp|u);
}
if (has[u^( (1<<n)-1 )])
{
int v=base+ (u^( (1<<n)-1 ));
//cout<<"v="<<v<<endl;
if (!vis[v]) dfs(v);
}
}
}
int main()
{
scanf("%d%d",&n,&m);
base=(1<<n);
memset(has,false,sizeof(has));
for (int i=1; i<=m; i++)
{
scanf("%d",&a[i]);
has[a[i]]=true;
}
memset(vis,false,sizeof(vis));
int ans=0;
for (int i=1; i<=m ;i++)
{
if (vis[a[i]+base]) continue;
ans++;
dfs(base+a[i]);
}
cout<<ans<<endl;
return 0;
}