P2679 NOIP2015T5 scroll array substring DP +

The meaning of problems: given two strings, the first sub-seeking in string to match the second, and the first sub-string and string matching according to the order of the second string;

Use the scroll array to optimize DP, otherwise it will MLE;

Set F [I] [J] [K] [0/1] F [I] [J] [K] [0/1] F [ I ] [ J ] [ K ] [ 0 / . 1 ] indicates whether to use a certain a string of the i-th character, and used in the k-th string a to string B matches the first j characters (not necessarily represent 0, 1 denotes a constant)

State transition equation:

f[i][j][k][0]=f[i−1][j][k][0]+f[i−1][j][k][1]f[i][j][k][0]=f[i-1][j][k][0]+f[i-1][j][k][1]f[i][j][k][0]=f[i1][j][k][0]+f[i1][j][k][1]

if(a[i]==b[j])

f[i][j][k][1]=f[i−1][j−1][k−1][1]+f[i−1][j−1][k−1][0]+f[i−1][j−1][k][1]f[i][j][k][1]=f[i-1][j-1][k-1][1]+f[i-1][j-1][k-1][0]+f[i-1][j-1][k][1]f[i][j][k][1]=f[i1][j1][k1][1]+f[i1][j1][k1][0]+f[i1][j1][k][1]

 

Attach Code:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int mod = 1000000007;
const int N = 1011;

int n,m,sum;
int f[2][N][N][2];
char a[N],b[N];

int main()
{
	scanf("%d%d%d",&n,&m,&sum);
	scanf("%s%s",a+1,b+1);
	f[0][0][0][0]=1;//初始化 
	for(int i=1;i<=n;i++){
		int op=i&1;
		f[op][0][0][0]=1;//初始化 
		for(int j=1;j<=min(i,m);j++)
		for(int k=1;k<=min(j,sum);k++){
			f[op][j][k][0]=f[op][j][k][1]=0;//滚动数组覆盖 
			f[op][j][k][0]=(f[op^1][j][k][0]+f[op^1][j][k][1])%mod;
			if(a[i]==b[j]){
				f[op][j][k][1]=((f[op^1][j-1][k-1][1]+f[op^1][j-1][k-1][0])%mod+f[op^1][j-1][k][1])%mod;
			}
		}
	}
	printf("%d",(f[n&1][m][sum][1]+f[n&1][m][sum][0])%mod);
	return 0;
}

Guess you like

Origin www.cnblogs.com/nnezgy/p/11366372.html