Longest Common Subsequence

Source

https://onlinejudge.u-aizu.ac.jp/problems/ALDS1_10_C

Description

Time Limit :  1 sec , Memory Limit : 131072 KB 

Longest Common Subsequence

For given two sequences XX and YY, a sequence ZZ is a common subsequence of XX and YY if ZZ is a subsequence of both XX and YY. For example, if X={a,b,c,b,d,a,b}X={a,b,c,b,d,a,b} and Y={b,d,c,a,b,a}Y={b,d,c,a,b,a}, the sequence {b,c,a}{b,c,a} is a common subsequence of both XX and YY. On the other hand, the sequence {b,c,a}{b,c,a} is not a longest common subsequence (LCS) of XX and YY, since it has length 3 and the sequence {b,c,b,a}{b,c,b,a}, which is also common to both XX and YY, has length 4. The sequence {b,c,b,a}{b,c,b,a}is an LCS of XX and YY, since there is no common subsequence of length 5 or greater.

Write a program which finds the length of LCS of given two sequences XX and YY. The sequence consists of alphabetical characters.

Input

The input consists of multiple datasets. In the first line, an integer qq which is the number of datasets is given. In the following 2×q2×q lines, each dataset which consists of the two sequences XX and YY are given.

Output

For each dataset, print the length of LCS of XX and YY in a line.

Constraints

  • 1q1501≤q≤150
  • 11≤ length of XX and Y1,000≤1,000
  • q20q≤20 if the dataset includes a sequence whose length is more than 100

Sample Input 1

3
abcbdab
bdcaba
abc
abc
abc
bc

Sample Output 1

4
3
2

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.

Code

 1 #include<stdio.h>
 2 #include<string.h>
 3 #define M 1001
 4 void Print_lCS(char x[],char y[]);
 5 int main()
 6 {
 7     char x[M],y[M];
 8     int q;
 9     scanf("%d",&q);
10     while(q--){
11         scanf("%s%s",x,y);
12         Print_lCS(x,y);
13     }
14 }
15 
16 void Print_lCS(char x[],char y[])
17 {
18     int nx = strlen(x);
19     int ny = strlen(y);
20     int i,j;
21     int c[nx+1][ny+1];
22     //边界条件
23     for(i = 0;i <= nx;i++)
24         c[i][0] = 0;
25     for(j = 0;j <= ny;j++)
26         c[0][j] = 0;
27     //
28     for(i = 1;i <= nx;i++){
29     for(j = 1;j <= ny;j++){
30         if(x[i-1] == y[j-1])
31                 c[i][j] = c[i-1][j-1] + 1;
32             else if(c[i][j-1] >= c[i-1][j])
33                 c[i][j] = c[i][j-1];
34             else
35                 c[i][j] = c[i-1][j];
36         }
37     }
38     printf("%d\n",c[nx][ny]);
39 }
c_code

猜你喜欢

转载自www.cnblogs.com/zjsyzmx0527/p/9898193.html