• HZAU 17:LCS


    17: LCS

    Time Limit: 1 Sec  Memory Limit: 128 MB
    Submit: 184  Solved: 43
    [Submit][Status][Web Board]

    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

    abxccdef
    abcxcdef
    3
    abccdef
    abcdef
    3

    Sample Output

    4
    6

    题目分析:设两个字符串分别为p和q,定义状态dp(i,j)表示p的前缀p(1~i)和q的前缀q(1~j)的满足题目要求的LCS的长度,定义g(i,j)表示满足题目要求的并且结尾字符为p(i)或q(j)(显然,这要求p(i)=q(j))的LCS的长度。
    的长度。则状态转移方程为:dp(i,j)=max(dp(i-1,j),dp(i,j-1),g(i,j))。

    代码如下:

    # include<iostream>
    # include<cstdio>
    # include<cstring>
    # include<algorithm>
    using namespace std;
    
    int k;
    char p[2105];
    char q[2105];
    int f[2105][2105];
    int g[2105][2105];
    int dp[2105][2105];
    
    int main()
    {
        //freopen("F.in","r",stdin);
        while(~scanf("%s%s%d",p+1,q+1,&k))
        {
            memset(f,0,sizeof(f));
            memset(g,0,sizeof(g));
            memset(dp,0,sizeof(dp));
            int n=strlen(p+1);
            int m=strlen(q+1);
            for(int i=1;i<=n;++i)
                for(int j=1;j<=m;++j)
                    if(p[i]==q[j]) f[i][j]=f[i-1][j-1]+1;
            for(int i=1;i<=n;++i){
                for(int j=1;j<=m;++j){
                    if(f[i][j]>=k){
                        g[i][j]=max(g[i][j],dp[i-k][j-k]+k);
                        if(f[i][j]>k)
                            g[i][j]=max(g[i][j],g[i-1][j-1]+1);
                    }
                    dp[i][j]=max(max(dp[i-1][j],dp[i][j-1]),g[i][j]);
                }
            }
            printf("%d
    ",dp[n][m]);
        }
        return 0;
    }
    

      

  • 相关阅读:
    288.软件开发过程与软件测试
    287.软件测试概述
    离散数学课程重点
    博客园美化
    渗透测试-Getshell总结
    C++迭代器
    每日一题2
    计算机网络面试总结(传输层)
    每日一题-1
    网络安全必备技能
  • 原文地址:https://www.cnblogs.com/20143605--pcx/p/5496726.html
Copyright © 2020-2023  润新知