zoukankan      html  css  js  c++  java
  • Coincidence (动态规划求最长公共子序列)(王道)

    题目描述:

    Find a longest common subsequence of two strings.

    输入:

    First and second line of each input case contain two strings of lowercase character a…z. There are no spaces before, inside or after the strings. Lengths of strings do not exceed 100.

    输出:

    For each case, output k – the length of a longest common subsequence in one line.

    样例输入:
    abcd
    cxbydz
    样例输出:
    2
     1 #include <iostream>
     2 #include<string.h>
     3 #include<cstdio>
     4 #define MAX(a,b) a>b?a:b
     5 #define N 200
     6 using namespace std;
     7 
     8 int main()
     9 {
    10     char str1[N];
    11     char str2[N];
    12     int line[N][N];
    13     while(scanf("%s %s",str1,str2)!=EOF){
    14         int len1=strlen(str1);
    15         int len2=strlen(str2);
    16 
    17         for(int i=0;i<=len1;i++)//初始化
    18             line[i][0]=0;
    19         for(int j=0;j<=len2;j++)
    20             line[0][j]=0;
    21         for(int i=1;i<=len1;i++){
    22             for(int j=1;j<=len2;j++){
    23                 if(str1[i-1]!=str2[j-1])//当前两个字符不相等
    24                     line[i][j]=MAX(line[i][j-1],line[i-1][j]);
    25                 else
    26                     line[i][j]=line[i-1][j-1]+1;//相等加一
    27             }
    28         }
    29         printf("%d
    ",line[len1][len2]);
    30 
    31     }
    32     return 0;
    33 }

    分析:line[x][y]求得str1前x个字符组成地前缀子串和str2前y个字符组成的前缀子串的最长公共子序列长度。

               若str1[x]==str2[y],即str1中的第x个字符和str2的第y个字符相同,同时由于它们都是各自前缀子串的最后一个字符,那么必存在一个最长公共子串以str1[x]或str2[y]结尾,其他部分等价于str1中前x-1个字符和str2中前y-1个字符的最长公共子串。所以这个子串的长度比line[x-1][y-1]又增加1;

               若str1[x]!=str2[y],此时其最长公共子串长度为str1中前x-1个字符和str2中前y个字符的最长公共子串长度与str1中前x-1个字符和str2中前y个字符的最长公共子串长度与str1中前x个字符和str2中前y-1个字符的最长公共子串长度的较大者,即两种情况下得到的最长公共子串都不会因为其中一个字符串又增加了一个字符长度发生改变。

       总结:最长公共子序列问题的递推条件:

                  line[0][j](0<=j<=m)=0;

                  line[i][0](0<=i<=n)=0;

          line[i][j]=line[i-1][j-1]+1;(str1[i]==str2[j])

          line[i][j]=max{line[i-1][j],line[i][j-1]};(str[i]!=str2[j])

  • 相关阅读:
    cocos2d-x 2.2 study ------------------------ 双击事件(转)
    cocos2d-x打包Android
    cocos2d-x在win7下的android交叉编译环境
    Cocos2d-x之CCImage深入分析
    Eclipse开发C/C++之使用技巧小结
    TortoiseSVN安装使用
    cocos2d-x 2.2 study ------------------------ CCCallFunC家族
    cocos2d-x改底层之动态改变UIListView中的某项在链表中的位置
    汇编语言,以10进制的方式显示数字
    JVM
  • 原文地址:https://www.cnblogs.com/xym4869/p/8629174.html
Copyright © 2011-2022 走看看