码迷,mamicode.com
首页 > 其他好文 > 详细

Longest Common Subsequence

时间:2018-11-02 21:43:17      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:one   data   nbsp   xmlns   ems   includes   round   clu   display   

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

 

Longest Common Subsequence

标签:one   data   nbsp   xmlns   ems   includes   round   clu   display   

原文地址:https://www.cnblogs.com/zjsyzmx0527/p/9898193.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!