首页 > 代码库 > HDU 1159 Common Subsequence

HDU 1159 Common Subsequence

题目:

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.
The program input is from a text file. Each data set in the file contains two strings representing the given sequences. The sequences are separated by any number of white spaces. The input data are correct. 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.

Input

abcfbc abfcab
programming contest 
abcd mnp

Output

4
2
0

Sample Input

abcfbc abfcab
programming contest 
abcd mnp

Sample Output

4
2
0
题意描述:
输入两串英文字符
计算并输出两串字符的最长公共子序列的长度
解题思路:
属于DP问题。双重循环遍历,若对应字符一样,则最长子序列数加一;
若不一样,选择第一串字符当前长度-1和第二串字符当前长度的最长公共子序列的长度和第一串字符当前长度和第二串字符当前长度-1的最长公共子序列的长度中较大的长度。
代码实现:
 1 #include<stdio.h>
 2 #include<string.h>
 3 char str1[1010],str2[1010];
 4 int maxlen[1010][1010];
 5 int main()
 6 {
 7     int l1,l2,i,j;
 8     while(scanf("%s%s",str1+1,str2+1) != EOF)
 9     {
10         l1=strlen(str1+1);
11         l2=strlen(str2+1);
12         for(i=0;i<=l1;i++)
13             maxlen[i][0]=0;
14         for(i=0;i<=l2;i++)
15             maxlen[0][i]=0;
16         for(i=1;i<=l1;i++)
17         {
18             for(j=1;j<=l2;j++)
19             {
20                 if(str1[i]==str2[j])
21                 maxlen[i][j]=maxlen[i-1][j-1]+1;
22                 else
23                 maxlen[i][j]=maxlen[i-1][j]>maxlen[i][j-1]?maxlen[i-1][j]:maxlen[i][j-1];
24             }
25         }
26         printf("%d\n",maxlen[l1][l2]);
27     }
28     return 0;
29 }

易错分析:

注意dp数组的初始化问题



HDU 1159 Common Subsequence