您的位置:首页 > 其它

Coincidence (动态规划求最长公共子序列)(王道)

2018-03-23 13:40 239 查看
题目描述:

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
;
11     char str2
;
12     int line

;
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\n",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])

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: