Description
有两种字符串S,T。长度分别为n,m。现在需要在S里面有序地选出k个子串,且在T中出现的顺序与这k个子串的顺序相同。问这k个子串最大的长度和
Solution
用DP,
设
fi,j,k,0/1
表示当前做到S串i位,T串j为,用了k个区间,当前区间可以扩展还是已经完结,
转移显然:
fi,j,k,1=max(fi−1,j−1,k,1,fi,j−1,k−1,0,fi−1,j,k−1,0)+1(Si=Tj)
fi,j,k,0=max(fi−1,j−1,k,0,fi−1,j−1,k,1,fi,j−1,k,0,fi−1,j,k,0)
复杂度: O(nmk)
Code
#include<cstdio>
#include<cstdlib>
#define fo(i,a,b) for(int i=a;i<=b;i++)
#define MAX(i,j,k) max(f[i][j][k][0],f[i][j][k][1])
#define fi f[i][j][k]
using namespace std;
const int N=1050;
int m,n,m1,ans;
int a[N],b[N];
int f[N][N][12][2];
int max(int q,int w){return q<w?w:q;}
int main()
{
freopen("string.in","r",stdin);
freopen("string.out","w",stdout);
int q,w;char ch=' ';
scanf("%d%d%d",&n,&m,&m1);
while(ch>'z'||ch<'a')ch=getchar();
a[1]=ch;fo(i,2,n)a[i]=getchar();
ch=' ';
while(ch>'z'||ch<'a')ch=getchar();
b[1]=ch;fo(i,2,m)b[i]=getchar();
fo(i,1,n)
fo(j,1,m)
fo(k,1,m1)
{
if(a[i]==b[j])fi[1]=max(f[i-1][j-1][k][1],max(f[i][j-1][k-1][0],f[i-1][j][k-1][0]))+1;
fi[0]=max(MAX(i-1,j-1,k),max(f[i][j-1][k][0],f[i-1][j][k][0]));
ans=max(ans,f[i][j][k][1]);
}
printf("%d\n",ans);
return 0;
}