最长公子序列 Longest Common Subsequence
2013-02-26 02:08
337 查看
设 X = (x0, x1, ... , x_(n-1) ), Y = (y0, y1, ... , y_(m-1) ), 那么用动态规划的方法,可以得到如下的阶段决策方程:
代码如下:
代码如下:
#include<stdio.h> #include<stdlib.h> #include<iostream> #include <cstring> using namespace std; int LCSubsequence(char* s1, char* s2){ if(!s1 || !s2) return 0; int len1 = strlen(s1); int len2 = strlen(s2); int* table = new int[len1*len2]; bool flag = false; for(int i=0; i<len2; i++){ if(*s1==*(s2+i)) flag = true; if(flag) table[i] = 1; } flag = false; for(int i=0; i<len1; i++){ if(*(s1+i)==*s2) flag = true; if(flag) table[i*len2] = 1; } if(len1>1 && len2>1) for(int i=1; i<len1; i++) for(int j=1; j<len2; j++) ( *(s1+i)==*(s2+j) )?( table[i*len2+j] = 1+ table[(i-1)*len2+j-1]): ( table[i*len2+j] = max( table[i*len2+j-1], table[(i-1)*len2+j]) ); int temp = table[len1*len2-1]; // delete [] table; return temp; } int main() { char* s1 = "abcdrgth"; char* s2 = "bdacrh45"; cout<<LCSubsequence(s1, s2)<<endl; getchar(); return 0; }上面的LCSubsequence函数,动态申请了一个一维数组table,用table来模拟二维数组。
相关文章推荐
- poj 1458Common Subsequence(最长公公子序列)
- uva10405 Longest Common Subsequence(最长公共序列)
- 最长递增子序列详解(longest increasing subsequence)
- [动态规划] 最长递增子序列 (Longest Increasing Subsequence)
- poj-2533 Longest Ordered Subsequence 【最长上升子序列】
- 最长上升子序列 LIS(Longest Increasing Subsequence)
- POJ 2127 Greatest Common Increasing Subsequence【最长公共递增子序列】
- hdu 1423 Greatest Common Increasing Subsequence (最长上升公共子序列)
- lintcode longest-increasing-continuous-subsequence 最长上升连续子序列
- OpenJudge 2757 最长上升子序列 / Poj 2533 Longest Ordered Subsequence
- LCS (Longest Common Subsequence) 字符串最长公共子串算法
- 最长上升子序列 LIS(Longest Increasing Subsequence)
- pku 2533 最长递增子序列 Longest Ordered Subsequence 解题报告
- HDU 1423 Greatest Common Increasing Subsequence 最长公共递增序列
- POJ 2533 Longest Ordered Subsequence (DP,最长递增序列)
- 求出最长非降子序列的长度--LIS:longest increasing subsequence
- 最长上升子序列 Longest Increasing Subsequence 输出其中一个序列 O(n^2) O(nlogn)
- 最长上升子序列 LIS(Longest Increasing Subsequence)(转)
- poj2533 Longest Ordered Subsequence(最长上升子序列个数)
- Longest Ordered Subsequence (最长有序(递增)序列)