hdu 1159 Common Subsequence

Problem 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. 
 
Sample Input
abcfbc abfcab
programming contest
abcd mnp
 
Sample Output
4
2
0
 
Source

题解:真心坑死....自己好不细心.....把dp[][]定义成了char类型....

代码:

 1 #include <stdio.h>
 2 #include <string.h>
 3 #include <math.h>
 4 #include <limits.h> 
 5 #include <algorithm>
 6 #include <iostream>
 7 #include <ctype.h>
 8 #include <iomanip>
 9 #include <queue>
10 #include <map>
11 #include <stdlib.h>
12 using namespace std;
13 
14 char a[1001],b[1001];
15 int dp[1001][1001];
16 
17 int LCS(int n,int m){
18     int i,j;
19     int len=max(n,m);
20     for(i=0;i<=len;i++){
21         dp[i][0]=0;
22         dp[0][i]=0;
23     }
24     for(i=1;i<=n;i++){
25         for(j=1;j<=m;j++){
26             if(a[i-1]==b[j-1]){
27                 dp[i][j]=dp[i-1][j-1]+1;
28             }
29             else{
30                 dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
31             }
32         }
33     }
34     return dp[n][m];
35 }
36 
37 int main()
38 {
39     while(~scanf("%s%s",&a,&b)){
40     int n=strlen(a);
41     int m=strlen(b);
42     int i,j;
43     int len=max(n,m);
44     for(i=0;i<=len;i++){
45         dp[i][0]=0;
46         dp[0][i]=0;
47     }
48     for(i=1;i<=n;i++){
49         for(j=1;j<=m;j++){
50             if(a[i-1]==b[j-1]){
51                 dp[i][j]=dp[i-1][j-1]+1;
52             }
53             else{
54                 dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
55             }
56         }
57     }
58     printf("%d
",dp[n][m]);
59     /*int i=n-1,j=m-1,count=k;
60     while(count!=0){
61         if(a[i]==b[j]){
62             cout<<a[i];
63             i--;
64             j--;
65             count--;
66         }
67         else if(dp[i][j-1]>dp[i-1][j]){
68             j--;
69         }
70         else{
71             i--;
72         }
73     }
74     cout<<endl;*/
75     }
76 }
原文地址:https://www.cnblogs.com/wangmengmeng/p/5019558.html