poj 1458 LCS(dp)全部最长公共子序列
来源:互联网 发布:淘宝网儿童玩具剑 编辑:程序博客网 时间:2024/06/16 07:45
http://poj.org/problem?id=1458
Common Subsequence
Time Limit: 1000MS Memory Limit: 10000KTotal Submissions: 35449 Accepted: 14100
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.
Input
The program input is from the std input. Each data set in the input contains two strings representing the given sequences. The sequences are separated by any number of white spaces. The input data are correct.
Output
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 abfcabprogramming contest abcd mnp
Sample Output
420
引进一个二维数组c[][],用c[i][j]记录X[i]与Y[j] 的LCS 的长度,b[i][j]记录c[i][j]是通过哪一个子问题的值求得的,以决定搜索的方向。
我们是自底向上进行递推计算,那么在计算c[i,j]之前,c[i-1][j-1],c[i-1][j]与c[i][j-1]均已计算出来。此时我们根据X[i] = Y[j]还是X[i] != Y[j],就可以计算出c[i][j]。
问题的递归式写成:
详细结题报告:
http://blog.csdn.net/yysdsyl/article/details/4226630
代码:
/*Source CodeProblem: 1458User: 201392210Memory: 4120KTime: 32MSLanguage: C++Result: Accepted*/#include <cstdio>#include <iostream>#include <cmath>#include <string.h>#include <stdlib.h>#include <algorithm>#include <stack>#include <vector>#include <queue>#define INF 0x3f3f3f3fusing namespace std;const int maxn=1000;char x[maxn],y[maxn];int l1,l2;int dp[maxn][maxn];void lcs(){memset(dp,0,sizeof(dp));for (int i = 1; i <= l1; ++i){for (int j = 1; j <= l2; ++j){if(x[i-1]==y[j-1])dp[i][j]=dp[i-1][j-1]+1;elsedp[i][j]=max(dp[i][j-1],dp[i-1][j]);}}}int main(){freopen("input.txt","r",stdin);while(~scanf("%s%s",x,y)){l1=strlen(x); l2=strlen(y);lcs();cout<<dp[l1][l2]<<endl;}return 0;}
0 0
- poj 1458 LCS(dp)全部最长公共子序列
- DP-POJ 1458 (LCS 最长公共子序列)
- poj 1458 LCS(最长公共子序列)
- poj DP LCS 最长公共子序列汇总
- 最长公共子序列 LCS DP
- DP 最长公共子序列 LCS
- DP---LCS 最长公共子序列问题
- DP之最长公共子序列 LCS
- 最长公共子序列(LCS DP)
- 最长公共子序列LCS(DP)
- 最长公共子序列LCS-DP
- ACM DP 最长公共子序列Lcs
- 最长公共子序列Lcs (dp)
- LCS 求最长公共子序列 dp
- poj 1458&poj 1159 最长公共子序列LCS
- POJ 1458最长公共子序列(DP)
- poj 1458最长公共子序列(LCS)
- 最长公共子序列(LCS, Longest Common Subsequence), POJ 1458
- linux内核分析--内核中的数据结构之双链表(续)
- POJ1789
- 有一些迷茫
- 数据结构的概述
- Ajax工作原理
- poj 1458 LCS(dp)全部最长公共子序列
- SVN与CVS的比较
- 电脑触摸屏上的鼠标事件触发
- php面向对象(基础)
- Java环境变量配置
- fit vs healthy
- DIRECT: in & on
- php之call_user_func();和call_user_func_array();
- 机器学习—第一课