poj之最长公共子序列和最长公共子串

来源:互联网 发布:龙华行知小学 编辑:程序博客网 时间:2024/06/07 06:31

题目:poj 1458   Common Subsequence

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.

思路:题目的意思是给定两个字符串,求他们的最长公共子序列,其中子序列是可以不连续的。该题目是典型的动态规划问题,令dp[i][j]表示s1的前i个字符与s2的前j个字符的最长公共子序列,则当s1[i]==s2[j]时,dp[i+1][j+1]=dp[i][j]+1,如果不等,则dp[i+1][j+1]=max{dp[i][j+1],dp[i+1][j]},具体代码如下:

#include<iostream>#include<vector>#include<string>using namespace std;int LCS(string s1,string s2){int length1 = s1.size(),length2 = s2.size(),i,j;vector<vector<int> > dp(length1+1);for(i = 0;i <= length1;++i){vector<int> tmp(length2+1,0);dp[i] = tmp;}for(i = 0;i < length1;++i){for(j = 0;j < length2;++j){if(s1[i] == s2[j])dp[i+1][j+1] = dp[i][j]+1;else dp[i+1][j+1] = max(dp[i][j+1],dp[i+1][j]);}}return dp[length1][length2];}int main(){string s1,s2;while(cin >> s1 >> s2){cout << LCS(s1,s2) << endl;}return 0;}

最长公共子串

思路:两者的区别是子串要求连续的,子序列不需要连续,所以在状态转移方程中的表现就是当s1[i] != s2[j]时,d[i][j] = 0。具体如下:

#include<iostream>#include<vector>#include<string>using namespace std;int LCS(string s1,string s2){int length1 = s1.size(),length2 = s2.size(),i,j,res = 0;vector<vector<int> > dp(2);//这里重复使用了数组空间,即所谓的用滚动数组来减少空间复杂度,上面的子序列也可以同样进行优化for(i = 0;i < 2;++i){vector<int> tmp(length2+1,0);dp[i] = tmp;}for(i= 0;i < length1;++i){int k = (i+1) & 1;for(j = 0;j < length2;++j){if(s1[i] == s2[j])//不相等默认为0{dp[k][j+1] = dp[k^1][j]+1;if(dp[k][j+1] > res)res = dp[k][j+1];}}}return res;}int main(){string s1,s2;while(cin >> s1 >> s2){cout << LCS(s1,s2) << endl;}return 0;}


4 0
原创粉丝点击