C-Bit Compression (暴力)

A binary string s of length N = 2n is given. You will perform the following operation n times :

- Choose one of the operators AND (&), OR (|) or XOR (^). Suppose the current string is S = s1s2...sk. Then, for all , replace s2i-1s2i with the result obtained by applying the operator to s2i-1 and s2i. For example, if we apply XOR to {1101} we get {01}.

After n operations, the string will have length 1.

There are 3n ways to choose the n operations in total. How many of these ways will give 1 as the only character of the final string.

輸入描述:

The first line of input contains a single integer n (1 ≤ n ≤ 18).

The next line of input contains a single binary string s (|s| = 2n). All characters of s are either 0 or 1.

輸出描述:

Output a single integer, the answer to the problem.

示例1

輸入

2 
1001

輸出

4

說明

The sequences (XOR, OR), (XOR, AND), (OR, OR), (OR, AND) works.

思路:直接暴力。。。。。。。。。。給的(1<<18)其實不大,暴力就整就完事了。。。

代碼:

#include<bits/stdc++.h>
using namespace std;
const int maxn=1e6+10;
char s[maxn];
int tr[maxn*5];
int res;

void dfs(int n){
    if(n==-1) {
        if(tr[2]==1) res++;
        return ;
    }
    int k=1<<n;
    for(int j=0;j<=2;j++){///遍歷三種運算
        int cou=0;///判斷是否都爲0
        for(int i=1;i<=k;i++){
            int tmp=i+k;
            if(j==0) tr[tmp]=tr[tmp*2-1]^tr[tmp*2];
            if(j==1) tr[tmp]=tr[tmp*2-1]|tr[tmp*2];
            if(j==2) tr[tmp]=tr[tmp*2-1]&tr[tmp*2];
            if(tr[tmp]==0)  cou++;
        }
        if(cou==k) continue;
        else dfs(n-1);
    }
}


int main(){
    int n;
    while(~scanf("%d",&n)){
        scanf("%s",s);
        int k=1<<n;
        for(int i=1;i<=k;i++) tr[i+k]=s[i-1]-'0';
        dfs(n-1);
        printf("%d\n",res);
        return 0;
    }
}

 

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