HZAUoj 1015: LCS (LCS变形)

来源:互联网 发布:mac珊瑚红是什么色号 编辑:程序博客网 时间:2024/05/22 17:51

1015: LCS

Time Limit: 1 Sec Memory Limit: 128 MB


Description

Giving two strings consists
of only lowercase letters, find the LCS(Longest Common Subsequence) whose all partition are not less than k in length.


Input

There are multiple test cases. In each test case, each of the first two lines is a string(length is less than 2100). The third line is a positive integer k. The
input will end by EOF.


Output

For each test case, output the length of the two strings’ LCS.


Sample Input

abxccdefabcxcdef3abccdefabcdef3


Sample Output

46


HINT

In the first test case, the answer is:

abxccdef

abcxcdef

The length is 4.

In the second test case, the answer is:

abccdef

abc def

The length is 6

题意:求LCS,加了一个条件,连续相等大于等于k的时候才算入进来。

设置一个c数组,c[i][j]为以a[i]、b[j]结尾的串的最大连续段长度。

然后dp转移方程dp[i][j]=max(dp[i-k][j-k]+k,dp[i-1][j-1]+1)(c[i][j]>=k)

dp[i, j] = max(dp[i-1, j], dp[i, j-1]) ai ≠ bj and c[i, j] >= k

#include<cstdio>#include<cstring>#include<cmath>#include<algorithm>using namespace std;char a[2105],b[2105];int dp[2105][2105];int c[2105][21005];int main(){int k;while(scanf("%s%s",a+1,b+1)!=EOF){scanf("%d",&k);int lena=strlen(a+1);int lenb=strlen(b+1);memset(dp,0,sizeof(dp));memset(c,0,sizeof(c));for(int i=1;i<=lena;i++){for(int j=1;j<=lenb;j++){if(a[i]==b[j])   c[i][j]=c[i-1][j-1]+1;}}for(int i=1;i<=lena;i++){for(int j=1;j<=lenb;j++){if(c[i][j]>=k){dp[i][j]=max(dp[i-k][j-k]+k,dp[i-1][j-1]+1);}else {dp[i][j]=max(dp[i-1][j],dp[i][j-1]);}}}printf("%d\n",dp[lena][lenb]);}return 0;} 



0 0
原创粉丝点击