洛谷 P2516 [HAOI2010]最长公共子序列
题目
题目描述
字符序列的子序列是指从给定字符序列中随意地(不一定连续)去掉若干个字符(可能一个也不去掉)后所形成的字符序列。令给定的字符序列X=“x0,x1,…,xm-1”,序列Y=“y0,y1,…,yk-1”是X的子序列,存在X的一个严格递增下标序列
ABCBDAB.
BACBBD.
输出样例#1:
4
7
题解
DP
f[i][j]表示两个字符串分别以i、j结尾时的最长公共子串的长度
r[i][j]表示两个字符串分别以i、j结尾时的最长公共子串的数量
很显然,f[i][j]就是由f[i-1][j]、f[i][j-1]、f[i-1][j-1]推过来的,所以只需要记住f[i-1][0~m-1]的状态就可已推出f[i][1~m]的状态
代码
#include<iostream>
#include<cstdio>
#include<cstring>
#define tt 100000000
using namespace std;
int n,m,now,pre;
int f[2][5005],r[2][5005];
char s1[5005],s2[5005];
int main()
{
scanf("%s",s1+1);n=strlen(s1+1)-1;
scanf("%s",s2+1);m=strlen(s2+1)-1;
for(int k=0;k<=m;k++) r[0][k]=1;
r[1][0]=1;now=1;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
f[now][j]=max(f[pre][j],f[now][j-1]);
r[now][j]=0;
if (s1[i]==s2[j]) f[now][j]=max(f[now][j],f[pre][j-1]+1);
if (s1[i]==s2[j]&&f[now][j]==f[pre][j-1]+1) r[now][j]+=r[pre][j-1];
if (f[pre][j]==f[now][j]) r[now][j]+=r[pre][j];
if (f[now][j-1]==f[now][j]) r[now][j]+=r[now][j-1];
if (f[pre][j-1]==f[now][j]) r[now][j]-=r[pre][j-1];
r[now][j]=(r[now][j]+tt)%tt;
}
now=pre;pre=(pre+1)%2;
}
printf("%d\n%d",f[pre][m],r[pre][m]);
return 0;
}