Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 9595 Accepted Submission(s): 3923
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.
1 #include <cstring>
2 #include <cstdlib>
3 #include <cstdio>
4 #define Max( a, b ) (a) > (b) ? (a) : (b)
5 using namespace std;
6
7 char s1[1005], s2[1005];
8
9 int dp[1005][1005];
10
11 int main()
12 {
13 int len1, len2;
14 while( scanf( "%s %s", s1, s2 ) != EOF )
15 {
16 memset( dp, 0, sizeof(dp) );
17 len1 = strlen( s1 ), len2 = strlen( s2 );
18 for( int i = 1; i <= len1; ++i )
19 {
20 for( int j = 1; j <= len2; ++j )
21 {
22 if( s1[i-1] == s2[j-1] )
23 {
24 dp[i][j] = dp[i-1][j-1] + 1;
25 }
26 else
27 {
28 dp[i][j] = Max ( dp[i-1][j], dp[i][j-1] );
29 }
30 }
31 }
32 printf( "%d\n", dp[len1][len2] );
33 }
34 return 0;
35 }
第二种处理方法:
#include <cstring>
#include <cstdlib>
#include <cstdio>
#define Max( a, b ) (a) > (b) ? (a) : (b)
using namespace std;
char s1[1005], s2[1005];
int dp[1005][1005];
int main()
{
int len1, len2;
while( scanf( "%s %s", s1+1, s2+1 ) != EOF )
{
memset( dp, 0, sizeof(dp) );
len1 = strlen( s1+1 ), len2 = strlen( s2+1 );
for( int i = 1; i <= len1; ++i )
{
for( int j = 1; j <= len2; ++j )
{
if( s1[i] == s2[j] )
{
dp[i][j] = dp[i-1][j-1] + 1;
}
else
{
dp[i][j] = Max ( dp[i-1][j], dp[i][j-1] );
}
}
}
printf( "%d\n", dp[len1][len2] );
}