C-Bit Compression (暴力)
程序员文章站
2024-03-12 23:47:32
...
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;
}
}
上一篇: Eclipse安装配置方法图文教程