hdu 1159 Common Subsequence

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. 
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

 

思路:

用一个数组c[i][j]来存从0到第一个字符串位置i与从0到第二个字符串位置j中出现的最长共有子序列的长度。如果字符串一中a[i]等于字符串二中b[j],那么c[i][j]=c[i-1][j-1],注意不是c[i-1][j]或者c[i][j-1],因为比如abc bbf,a[1]==b[1]此时c[1][1]=1,c[0][1]=0,c[1][0]=1;c[0][0]=0,如果c[1][1]=c[1][0]+1,那么就重复计算了bbf中的两个b,事实上只能算一个。当a[i]!=b[j]时,c[i][j]=max(c[i-1][j],c[i][j-1])。

动态方程:

c[i][j]=c[i-1][j-1} (a[i]==a[j])

c[i][j]=max(c[i-1][j],c[i][j-1]) (a[i]!=a[j])

 

源代码:

 

 1 #include <iostream>
 2 #include<cstring>
 3 #include<stdio.h>
 4 using namespace std;
 5 char a[1000],b[1000];
 6 int c[1000][1000];
 7 int len_a,len_b;
 8 int i,j;
 9 int dp(int a,int b)
10 {
11     if(a>=0&&b>=0)return c[a][b];
12     else return 0;
13 }
14  
15 int main()
16 {
17   while(scanf("%s %s",a,b)!=EOF)
18   {   len_a=strlen(a);
19       len_b=strlen(b);
20       for(i=0;i<len_a;i++)
21       {
22           for(j=0;j<len_b;j++)
23           {
24  
25               if(a[i]==b[j])
26                c[i][j]=dp(i-1,j-1)+1;
27               else c[i][j]=(dp(i-1,j)>dp(i,j-1))?dp(i-1,j):dp(i,j-1);
28           }
29       }
30  
31   printf("%d\n",c[i-1][j-1]);
32   }
33     return 0;
34 }

 

 

 

posted @ 2013-08-06 00:28  小の泽  阅读(151)  评论(0编辑  收藏  举报