牛客网暑期ACM多校训练营(第七场)C:Bit Compression(思维)

链接:https://www.nowcoder.com/acm/contest/145/C

时间限制:C/C++ 2秒,其他语言4秒
空间限制:C/C++ 262144K,其他语言524288K
Special Judge, 64bit IO Format: %lld
题目描述
A binary string s of length N = 2 n 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 = s 1 s 2 . . . s k . Then, for all 1 i k 2 , replace s 2 i 1 s 2 i with the result obtained by applying the operator to s 2 i 1 and s 2 i . For example, if we apply XOR to {1101} we get {01}.

After n operations, the string will have length 1.

There are 3 n 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 | = 2 n ) . 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.

题解:暴力的复杂度是 3 n 的,只需要再优化一点点!
• 如果剩下了16个变量,可能性只有65536个。
• 预处理他们,得到以个 3 n 4 的做法。
• 事实上,直接暴力,常数优化即可

#include<bits/stdc++.h>
using namespace std;
const int MAX=1e6+10;
const int MOD=1e9+7;
typedef long long ll;
char s[20][MAX];
ll d[5][MAX];
ll cal(int x,int n)
{
    if(d[n][x]!=-1)return d[n][x];
    if(n==0)return d[0][x]=x;
    ll tot=0,y=0;
    for(int i=0,j=0;i<(1<<n);i+=2,j++)y+=(1<<j)*(((x>>i)&1)^(x>>(i+1)&1));tot+=cal(y,n-1);y=0;
    for(int i=0,j=0;i<(1<<n);i+=2,j++)y+=(1<<j)*(((x>>i)&1)&(x>>(i+1)&1));tot+=cal(y,n-1);y=0;
    for(int i=0,j=0;i<(1<<n);i+=2,j++)y+=(1<<j)*(((x>>i)&1)|(x>>(i+1)&1));tot+=cal(y,n-1);y=0;
    return d[n][x]=tot;
}
ll dfs(int n)
{
    if(n<=4)
    {
        int x=0;
        for(int i=0;i<(1<<n);i++)x+=(1<<i)*(s[n+1][i]-'0');
        return d[n][x];
    }
    ll tot=0;
    for(int i=0,j=0;i<(1<<n);i+=2,j++)s[n][j]=((s[n+1][i]-'0')^(s[n+1][i+1]-'0'))+'0';tot+=dfs(n-1);
    for(int i=0,j=0;i<(1<<n);i+=2,j++)s[n][j]=((s[n+1][i]-'0')|(s[n+1][i+1]-'0'))+'0';tot+=dfs(n-1);
    for(int i=0,j=0;i<(1<<n);i+=2,j++)s[n][j]=((s[n+1][i]-'0')&(s[n+1][i+1]-'0'))+'0';tot+=dfs(n-1);
    return tot;
}
int main()
{
    memset(d,-1,sizeof d);
    for(int i=0;i<(1<<16);i++)cal(i,4);//预处理
    int n;
    cin>>n;
    scanf("%s",s[n+1]);
    cout<<dfs(n)<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Mitsuha_/article/details/81559898