[Blue Bridge Cup] 101 Strings in Group B of the 2019 National Championships (dfs pruning)

"01 string" refers to a string consisting of 0s and 1s.
Mr. Garantou is a die-hard fan of Rocket Girl 101. He wants to know
how many strings of 01 with a length of 30 contain the substring "101".

Thought analysis:

In fact, dfs is used to enumerate 2^30 cases. If pure violence is to enumerate each string of length 30, add a loop to determine whether it contains the substring "101". Although there is no time limit for this question, as long as you fill in the results, we must have an optimization heart!

In the process of enumeration, that is, in the string length <=30, if 101 strings have been found, then enumeration is not needed later. For example, take a length of 4 as an example. 1010 1011 The first 3 digits already have "101", so it doesn't matter what the fourth digit is. That is to say, if the current cur already satisfies "101", then the remaining numbers after cur do not need to be enumerated, because they already contain "101" no matter what the result is. Therefore, n-cur is left behind. -1 number, there are pow(2,n-cur-1) cases. Just add cnt directly.
The code above:

#include <iostream>
#include <cmath>
using namespace std;

long long a[40], cnt;
long long n = 30;

void dfs(int cur)
{
    
    
	if(cur >= n)	
	{
    
    
		return;
	}
	if(a[cur] == 1 && a[cur-1] == 0 && a[cur-2] == 1)
	{
    
    
		cnt+=pow(2,n-cur-1);
//		for(int i = 0;i <= cur;i++) cout<<a[i]<<" ";
//		cout<<endl<<cnt<<endl;
		return;
	}
	a[cur+1] = 0;
	dfs(cur+1);
	a[cur+1] = 1;
	dfs(cur+1);
}

int main()
{
    
    
	dfs(-1);
	cout<<cnt<<endl;
}

Answer: 1046810092

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324926559&siteId=291194637