链接:https://www.nowcoder.com/acm/contest/145/C
来源:牛客网
Bit Compression
时间限制:C/C++ 2秒,其他语言4秒
空间限制:C/C++ 262144K,其他语言524288K
Special Judge, 64bit IO Format: %lld
题目描述
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.
题意:给你一个n,再给你一个长度为2的n次方的01串。每次字符串可以选择三种操作:& | ^。选择之后,相邻的字符按这个操作合并:比如 1101 选择^ 则 1^1=0 0^1=1; 然后字符串就变成了01。继续操作直到剩余一个字符。问你最后只剩一个1的方法总数有多少种。
思路:
比赛的时候不敢暴力,再说过的人数那么少。。。实际上就是纯暴力,dfs的话题解虽然说要剪枝,但是其实不减枝也能过。我看到一个人用map直接暴力也过了。。。
于是代码:
#include<bits/stdc++.h>
using namespace std;
map<string,int> mp[20];
map<string,int>::iterator it;
int main()
{
int n;
string s,sa,sb,sc;
cin>>n>>s;
mp[n][s]=1;
for(int i=n;i>=1;i--)
{
for(it=mp[i].begin();it!=mp[i].end();it++)
{
s=it->first;
int s1=it->second;
int len=1<<i;
sa=sb=sc="";
for(int j=0;j<len;j+=2)
{
sa+=((s[j]-'0')&(s[j+1]-'0'))+'0';
sb+=((s[j]-'0')^(s[j+1]-'0'))+'0';
sc+=((s[j]-'0')|(s[j+1]-'0'))+'0';
}
mp[i-1][sa]+=s1;
mp[i-1][sb]+=s1;
mp[i-1][sc]+=s1;
}
}
cout<<mp[0]["1"]<<endl;
return 0;
}
附dfs(用的别人的代码,侵删):
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N=1e6+5;
int tree[N*50];
char str[N];
int res;
void dfs(int n)
{
if(n==-1)
{
if(tree[1]==1)
res++;
return ;
}
int k=1<<n;
for(int j=0; j<=2; j++)
{
int cou=0;
for(int i=0; i<k; i++)
{
int tmp=i+k;
if(j==0)
tree[tmp]=tree[tmp*2]^tree[tmp*2+1];
else if(j==1)
tree[tmp]=tree[tmp*2]|tree[tmp*2+1];
else
tree[tmp]=tree[tmp*2]&tree[tmp*2+1];
if(tree[tmp]==0)
cou++;
}
if(cou==k)
continue;
else
dfs(n-1);
}
}
int main()
{
int n;
scanf("%d",&n);
scanf("%s",str);
int k=1<<n;
for(int i=0; i<k; i++)
tree[i+k]=str[i]-'0';
dfs(n-1);
printf("%d\n",res);
return 0;
}