Newcoder 145 C.Bit Compression(dp+dfs)

Description

This paper presents a 010101 string of sss with a length of N=2nN=2^nN=2n, and performs nnn operations. Each operation selects one of the three operations: logical and, logical or, logical exclusive or. The result of two adjacent bits of sss string is formed into a new string. Obviously, the new string length is the same as before. After nnn operations, sss string has only one bit. There are 3n3^n3n possible operation schemes. How many operators are there The case made the final result 111

Input

Enter an integer n n n in the first line, and then enter a 010101 string s(1 ≤ n ≤ 18)s(1\le n\le 18)s(1 ≤ n ≤ 18) with a length of 2n2^n2n

Output

Output the number of schemes with the result of operation 111

Sample Input

2
1001

Sample Output

4

Solution

Direct burst search, dpdpdp preprocess all results of n ≤ 4n\le 4n ≤ 4, search for the answer when n=4n=4n=4

Code

#include<cstdio>
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int Solve(int x,int sta)
{
	int res=0,a[20];
	while(x)
	{
		a[res++]=x%2;
		x/=2;
	}
	if(res&1)a[res++]=0;
	int ans=0;
	if(sta==0)
		for(int i=res-1;i>=0;i-=2)ans=ans*2+(a[i]&a[i-1]);
	else if(sta==1)
		for(int i=res-1;i>=0;i-=2)ans=ans*2+(a[i]|a[i-1]);
	else
		for(int i=res-1;i>=0;i-=2)ans=ans*2+(a[i]^a[i-1]);
	return ans;
}
int deal(string s)
{
	int x=0;
	for(int i=0;i<s.size();i++)x=2*x+s[i];
	return x;
}
int ans,dp[(1<<16)+5][5];
void dfs(string s,int n)
{
	if(n==4)
	{
		ans+=dp[deal(s)][4];
		return ;
	}
	string t;
	t.clear();
	for(int i=0;i<s.size();i+=2)t.push_back(s[i]&s[i+1]);
	dfs(t,n-1);
	t.clear();
	for(int i=0;i<s.size();i+=2)t.push_back(s[i]|s[i+1]);
	dfs(t,n-1);
	t.clear();
	for(int i=0;i<s.size();i+=2)t.push_back(s[i]^s[i+1]);
	dfs(t,n-1);
}
int main()
{
	int n;
	string s;
	cin>>n>>s;
	for(int i=0;i<s.size();i++)s[i]-='0';
	dp[1][0]=1;
	for(int i=1;i<(1<<16);i++)
		for(int j=1;j<=4;j++)
			 dp[i][j]=dp[Solve(i,0)][j-1]+dp[Solve(i,1)][j-1]+dp[Solve(i,2)][j-1];
	if(n<=4)printf("%d\n",dp[deal(s)][n]);
	else
	{
		ans=0;
		dfs(s,n);
		printf("%d\n",ans);
	}
	return 0;
}

Posted by carnold on Mon, 30 Dec 2019 10:44:30 -0800