牛客网多校练习7 Bit Compression (暴力+map容器的计数使用方法)

链接:https://www.nowcoder.com/acm/contest/145/C
来源:牛客网
 

题目描述

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.
#include<bits/stdc++.h>
using namespace std;

const int maxn=20;

map<string,int> mp[maxn];
map<string,int>::iterator it;

string s,sa,sb,sc;
int n;
/*
题目大意:给定二进制串,和三种对应的放缩方式,
每次长度递减一倍,然后计数最终压缩成串1的情况组合数。

暴力大法好啊。。。。
但这道题参照了别人的代码也可以用状压写,用map作为
状压计数的容器,不断在新的长度中插入上一个长度压缩来的字符串,并累加其计数。

另外还有DFS做法,比赛时找数学规律找崩了。

*/

int main()
{
    cin>>n>>s;
    mp[n][s]=1;
    for(int i=n;i>=1;i--)
    {
        for(it=mp[i].begin();it!=mp[i].end();it++)
        {
            int cnt=it->second;
            string ss=it->first;
            sa=sb=sc="";///置空
            int len=1<<i;

            for(int j=0;j<len;j+=2)
            {
                sa+=((ss[j]-'0')  |  (ss[j+1]-'0'))+'0';
                sb+=((ss[j]-'0') ^ (ss[j+1]-'0'))+'0';
                sc+=((ss[j]-'0') & (ss[j+1]-'0'))+'0';
            }
            mp[i-1][sa]+=cnt;
            mp[i-1][sb]+=cnt;
            mp[i-1][sc]+=cnt;
        }
    }

    cout<<mp[0]["1"]<<endl;

    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_37451344/article/details/81592295
BIT