zoukankan      html  css  js  c++  java
  • POJ 1458 Common Subsequence(LCS最长公共子序列)

    POJ 1458 Common Subsequence(LCS最长公共子序列)解题报告

    题目链接:http://acm.hust.edu.cn/vjudge/contest/view.action?cid=87730#problem/F

    题目:

    Common Subsequence
    Time Limit: 1000MS   Memory Limit: 10000K
    Total Submissions: 43388   Accepted: 17613

    Description

    A subsequence of a given sequence is the given sequence with some elements (possible none) left out. Given a sequence X = < x1, x2, ..., xm > another sequence Z = < z1, z2, ..., zk > is a subsequence of X if there exists a strictly increasing sequence < i1, i2, ..., ik > of indices of X such that for all j = 1,2,...,k, xij = zj. For example, Z = < a, b, f, c > is a subsequence of X = < a, b, c, f, b, c > with index sequence < 1, 2, 4, 6 >. Given two sequences X and Y the problem is to find the length of the maximum-length common subsequence of X and Y.

    Input

    The program input is from the std input. Each data set in the input contains two strings representing the given sequences. The sequences are separated by any number of white spaces. The input data are correct.

    Output

    For each set of data the program prints on the standard output the length of the maximum-length common subsequence from the beginning of a separate line.

    Sample Input

    abcfbc         abfcab
    programming    contest 
    abcd           mnp

    Sample Output

    4
    2
    0

    题目大意:
    给出两个字符串,求两字符串的最长公共子序列。

    分析:
    很明显用LCS,时间复杂度O(nm),其中n,m是序列A和B的长度。当s1[i-1]==s2[k-1]时,d(i,k)=d(i-1,k-1)+1,否则,
    d(i,k)=max{d(i-1,k),d(i,k-1)}。

    代码:
     1 #include<cstdio>
     2 #include<iostream>
     3 #include<cstring>
     4 using namespace std;
     5 
     6 const int maxn=1005;
     7 
     8 int dp[maxn][maxn];
     9 
    10 int max(int a,int b)
    11 {
    12     return a>b?a:b;
    13 }
    14 
    15 int main()
    16 {
    17     char s1[maxn],s2[maxn];
    18     while(scanf("%s%s",s1,s2)!=EOF)
    19     {
    20         int m=strlen(s1);
    21         int n=strlen(s2);
    22         memset(dp,0,sizeof(dp));
    23         for(int i=1;i<=m;i++)
    24         {
    25             for(int k=1;k<=n;k++)
    26             {
    27                 if(s1[i-1]==s2[k-1])   //s1和s2相等,dp+1
    28                     dp[i][k]=dp[i-1][k-1]+1;
    29                 else                   //s1和s2不相等时看下一个
    30                     dp[i][k]=max(dp[i-1][k],dp[i][k-1]);
    31             }
    32         }
    33         printf("%d
    ",dp[m][n]);
    34     }
    35     return 0;
    36 }


  • 相关阅读:
    3、SpringBoot+MybatisPlus整合-------代码生成器
    2、SpringBoot+MybatisPlus整合-------BaseCRUD
    1、SpringBoot+MybatisPlus整合
    11、SpringBoot------定时任务
    4、SpringBoot------邮件发送(2)
    3、SpringBoot------邮件发送(1)
    2.初识CronTrigger
    3.初识Cron表达式
    1.初识Quartz
    9、SpringBoot+Mybatis整合------动态sql
  • 原文地址:https://www.cnblogs.com/ttmj865/p/4731806.html
Copyright © 2011-2022 走看看