(Blue Bridge Cup 13th Provincial Competition) G: Building Block Painting (Dynamic Programming)

Read in an n, ask how many different ways there are, and the answer is modulo 1e9+7.

Analysis: This question is a dynamic programming. Let f[i][0] represent the number of solutions in the first i column currently completed, f[i][1] represent the current completion of the first i-1 column, and the i-th column After finishing the number of solutions of the previous one, f[i][2] indicates that the first i-1 column is currently completed, and the current i-th column has completed the number of solutions of the next one . Then the answer is f[n][0]

The derivation of the dynamic transfer equation is as follows:

First look at which states f[i][0] can transition from:

If we currently want to put such a building block , then it is obviously recursive by f[i-1][0]. What if we put such a building block? , that is recursive by f[i-1][2], that is to say, the i-1th column has already spelled the following square. Similarly, f[i-1][1] can be recursive, That is, put such blocks in the i-th column: , do you think that this is all the case, in fact, this is not all the case, there is the last case, that is to put together a block like this at the top and bottom , which is determined by f [i-2][0] is obtained recursively, and this is the number of all cases.

That is to say , the recursive transition equation of f[i][0] is f[i][0]=(f[i-1][1]+f[i-1][2]+f[i-1 ][0]+f[i-2][0])%mod

Let's take a look at the recurrence equation of f[i][1]. This is easier to consider. One is to put such a building block:

This situation is obtained recursively on the basis of f[i-2][0]. Another situation is to put such blocks: , this situation is obtained on the basis of f[i-1][2], and f[i][1] is obtained recursively from these two situations.

That is to say , the transfer equation of f[i][1] is f[i][1]=(f[i-2][0]+f[i-1][2])%mod

 In the same way, the transfer equation of f[i][2] is f[i][2]=(f[i-2][0]+f[i-1][1])%mod

It should be noted that the initialization should be set to f[0][0]=1, and the recursive equation involves f[i-2][], so some recursive equations should be performed in the case of i>=2 , to prevent out-of-bounds

After analyzing this, the topic of this topic is basically analyzed, and the code is attached below

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<map>
#include<set>
using namespace std;
const int mod=1e9+7;
const int N=1e7+10;
long long f[N][3];
int main()
{
	int n;
	scanf("%d",&n);
	f[0][0]=1;
	for(int i=1;i<=n;i++)
	{
		f[i][0]=(f[i-1][0]+f[i-1][1]+f[i-1][2])%mod;
		if(i>=2) 
		{
			f[i][0]=(f[i][0]+f[i-2][0])%mod;
			f[i][1]=(f[i-2][0]+f[i-1][2])%mod;
			f[i][2]=(f[i-2][0]+f[i-1][1])%mod;
		}
	}
	printf("%lld",f[n][0]%mod);
	return 0;
}

Guess you like

Origin blog.csdn.net/AC__dream/article/details/124066067