首页 > 代码库 > poj之最长公共子序列

poj之最长公共子序列

题目: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][j]=dp[i-1][j-1]+1,如果不等,则dp[i][j]=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;
}