首页 > 代码库 > 最长公共子序列(动态规划)

最长公共子序列(动态规划)

#include<iostream>
#include<vector>
#include<iterator>
#include<algorithm>
#include<string>
using namespace std;

/*
*最长公共子序列(动态规划)
*/
vector<vector<int>> c;//c[i][j]记录串a[0..i]与串b[0..j]之间的最长公共子序列的长度
vector<vector<int>> b;//b[i][j]记录c[i][j]的值是由哪一个子问题的解得到的

void LCSLength(string m,string n)
{
	//初始化c、b数组
	c = vector<vector<int>>(m.length()+1,vector<int>(n.length()+1,0));//0行0列空余
	b = vector<vector<int>>(m.length()+1,vector<int>(n.length()+1,0));
	
	//构造数组C
	for (unsigned i = 1; i <= m.length() ; i++)
		for (unsigned j = 1; j <= n.length(); j++)
		{
			if(m[i-1]==n[j-1])
			{c[i][j] = c[i-1][j-1]+1;b[i][j] = 1;}
			else
			{
				if (c[i-1][j]>=c[i][j-1])
				{
					c[i][j] = c[i-1][j];b[i][j] = 2;
				}
				else
				{
					c[i][j] = c[i][j-1];b[i][j] = 3;
				}
			}
		}
}

void PrintRes(string m,int i,int j)
{
	if(i == 0 || j == 0) return;
	if(b[i][j] == 1) 
	{
		PrintRes(m,i-1,j-1);
		cout<<m[i-1];
	}
	else
	{
		if(b[i][j] == 2) PrintRes(m,i-1,j);
		else
		{
			PrintRes(m,i,j-1);
		}
	}
}
int main()
{
	string a,b;
	cin>>a;
	cin>>b;
	//计算最长公共子序列的集合
	LCSLength(a,b);
	cout<<"最长公共子序列为:"<<endl;
	PrintRes(a,a.length(),b.length());
	return 0;
}

最长公共子序列(动态规划)