CodeForces 986C AND Graph 位运算+弱连通分量

C. AND Graph
time limit per test:4 seconds
memory limit per test:256 megabytes
input:standard input
output:standard output

You are given a set of size m with integer elements between 0 and 2n1 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.

Input

In the first line of input there are two integers n and m (0n221m2n).

In the second line there are m integers a1,a2,,am (0ai<2n) — the elements of the set. All ai are distinct.

Output

Print the number of connected components.

Examples
Input
Copy
2 3
1 2 3
Output
Copy
2
Input
Copy
5 5
5 19 10 20 12
Output
Copy
2
Note

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值