<OJ_Sicily>Longest Common Subsequence
来源:互联网 发布:二次元动态桌面软件 编辑:程序博客网 时间:2024/06/05 19:40
Description
Given a sequence A = < a1, a2, ..., am >, let sequence B = < b1, b2, ..., bk > be a subsequence of A if there exists a strictly increasing sequence ( i1<i2<i3 ..., ik ) of indices of A such that for all j = 1,2,...,k, aij = bj. For example, B = < a, b, c, d > is a subsequence of A= < a, b, c, f, d, c > with index sequence < 1, 2, 3 ,5 >.
Given two sequences X and Y, you need to find the length of the longest common subsequence of X and Y.
Input
The input may contain several test cases.
The first line of each test case contains two integers N (the length of X) and M(the length of Y), The second line contains the sequence X, the third line contains the sequence Y, X and Y will be composed only from lowercase letters. (1<=N, M<=100)
Input is terminated by EOF.
Output
Output the length of the longest common subsequence of X and Y on a single line for each test case.
题目解释:使用动态规划求解最长公共子序列。这道题在前面有一样的题目。原理可以参考前面的博文。
解题思路:使用动态规划实现最长公共子序列的求解.假设LCS(Xi,Yj) 表示的是Xi和Yj这两个序列的最长公共子序列的解,则有
1.若Xi == Yj,那么LCS(Xi,Yj) = LCS(Xi-1,Yj-1) + 1
2.若Xi != Yj ,那么LCS(Xi,Yj) = max( LCS(Xi-1,Yj) , LCS(Xi,Yj-1) )
<pre name="code" class="cpp">#include <iostream>#include <algorithm>#include <string.h>using namespace std;int c[100][100];int main(int argc, const char * argv[]) { // insert code here... int len_X, len_Y; char strX[100], strY[100]; while (cin >> len_X >> len_Y) { int i,j; for (i = 0; i < len_X; i++) { cin >> strX[i]; } for (j = 0; j < len_Y; j++) { cin >> strY[j]; } memset(c, 0, sizeof(c)); for (i = 0; i <= len_X; i++) { for (j = 0; j <= len_Y; j++) { if (i == 0 || j == 0) c[i][j] = 0; else if (strX[i-1] == strY[j-1] ) c[i][j] = c[i-1][j-1] + 1; else c[i][j] = max(c[i-1][j], c[i][j-1]); } } cout << c[len_X][len_Y] << endl; } return 0;}
- <OJ_Sicily>Longest Common Subsequence
- longest common subsequence
- Longest Common Subsequence
- 10405 Longest Common Subsequence
- UVa10405 - Longest Common Subsequence
- 10405 - Longest Common Subsequence
- UVa10405 - Longest Common Subsequence
- UVaOJ10405 - Longest Common Subsequence
- 10405 - Longest Common Subsequence
- uva10405 Longest Common Subsequence
- 10405 - Longest Common Subsequence
- 10405 - Longest Common Subsequence
- Uva10405 Longest Common Subsequence
- UVaOJ_10405 - Longest Common Subsequence
- Longest common subsequence / substring
- uva10405 - Longest Common Subsequence
- longest common subsequence 问题
- [DP]Longest Common Subsequence
- numba版 自适应差分进化算法 速度超快 可以求解约束问题
- Android学习
- Eclipse中SVN的安装步骤(两种)和使用方法
- java核心机制之JVM
- jQuery.extend() 函数详解
- <OJ_Sicily>Longest Common Subsequence
- linux nc命令常用用法
- View的事件分发机制
- MySql-日志详解
- 在浏览器中输入www.baidu.com后执行的全部过程
- Acdream 1214 Nice Patterns Strike Back (矩阵乘法 + 状态压缩)
- iOS_高效开发之道
- 初识Swift
- iOS开发:==、isEqual与isEqualToString判断是否相等