codeforces 449D Jzzhu and Numbers 容斥+DP

很有意思的一題,題意是找到有多少個子序列,使得子序列每個元素的&值爲0。

我們先考慮,如果每個都是0,那麼方案顯然是2^n-1,但是可能算多了。分別考慮第1位到第20位一定是1的情況,因爲是&運算,選的一定是該位爲1。然後統計兩位的,三位的。。。答案就是 ∑ -1^d(x) * (  2^f(x )-1 )  ,x的範圍的[0,1<<20),d(x)表示x改爲二進制有多少個0,f(x)表示的是滿足 ai&x == x的數字個數。

現在的問題關鍵是怎麼計算f(x),因爲直接暴力顯然是不靠譜的,我們用dp[i][j] 表示某個狀態,j是一個二進制數,我們不妨記j的低 i 位爲x0,其他高位爲x1,即 x1x0 == j ,x0中的1表示某個數的此位一定是1,0表示這個數的這一位可以是任意的數;而在x1中,1表示這個數的此位一定是1,0表示這個數的此位一定是0,滿足這種情況的數字個數。顯然dp[19][j] = f(j)。我們可以很容易得到轉移方程(具體見代碼)。

//#pragma comment(linker, "/STACK:102400000,102400000")
#include<cstdio>
#include<cstring>
#include<vector>
#include<queue>
#include<cmath>
#include<cctype>
#include<string>
#include<algorithm>
#include<iostream>
#include<ctime>
#include<map>
#include<set>
using namespace std;
#define MP(x,y) make_pair((x),(y))
#define PB(x) push_back(x)
typedef long long LL;
//typedef unsigned __int64 ULL;
/* ****************** */
const LL INF=1LL<<60;
const double INFF=1e100;
const double eps=1e-8;
const int mod=1000000007;
const int NN=100005;
const int MM=1000010;
/* ****************** */

int dp[20][1<<20];
int a[1<<20];

int q_pow(int x,int n,LL mod)
{
    LL ans=1,xx=x;
    for(;n>0;n>>=1)
    {
        if(n&1)ans=ans*xx%mod;
        xx=xx*xx%mod;
    }
    return (int)ans;
}

int main()
{
    int n,i,j,mask=1<<20;
    int ans,t,tt;
    scanf("%d",&n);
    for(i=1;i<=n;i++)
        scanf("%d",&a[i]);

    memset(dp,0,sizeof(dp));
    for(i=1;i<=n;i++)
    {
        if(a[i]&1)
        {
            dp[0][ a[i] ]++;
            dp[0][ a[i]^1 ]++;
        }
        else
        {
            dp[0][ a[i] ]++;
        }
    }
    for(i=0;i<19;i++)
        for(j=0;j<mask;j++)
        {
            t=1<<(i+1);
            if(j&t)
            {
                dp[i+1][j]+=dp[i][j];
                dp[i+1][ j-t ]+=dp[i][j];
            }
            else
            {
                dp[i+1][j]+=dp[i][j];
            }
        }

    ans=0;
    for(j=0;j<mask;j++)
    {
        t=1;
        for(i=0;i<20;i++)
            if((1<<i)&j)
                t=-t;
        tt=q_pow(2,dp[19][j],mod);
        tt--;
        if(tt<0)tt+=mod;
        ans+=t*tt;
        if(ans>=mod)ans-=mod;
        if(ans<0)ans+=mod;
    }

    printf("%d\n",ans);

    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章