一本通1265:【例9.9】最长公共子序列 暨 LCS DP求解

原题传送门

这是一道求解(LCS)(最长公共子序列)长度的模板题

状态的定义:定义(dp[i][j])是在(A)(1)(i)(B)(1)(j)(LCS)长度

状态的转移:

  • (A[i]=b[j]) (dp[i][j]=dp[i-1][j-1]+1)
  • (A[i] e b[j]) (dp[i][j]=max(dp[i][j-1],dp[i-1][j]))

(Code)

#include<iostream>
#include<cstdio>
#include<string>
using namespace std;
inline void read(int &x){
	int f=1;
	char ch=getchar();
	x=0;
	while(ch<'0'||ch>'9'){
		if(ch=='-') f=-1;
		ch=getchar();
	}
	while(ch>='0'&&ch<='9'){
		x=x*10+ch-'0';
		ch=getchar();
	}
	x*=f;
}
int len1,len2;
int dp[1001][1001]={0};
string str1,str2;
inline void LCS(int p,int q){	//A长度为p,B长度为q 
	for(int i=1;i<=p;i++){
		for(int j=1;j<=q;j++){
			if(str1[i-1]==str2[j-1]) dp[i][j]=dp[i-1][j-1]+1;	//一定注意下标 
			else dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
		}
	}
}
int main(){
	cin>>str1>>str2;
	len1=str1.size();
	len2=str2.size();
	LCS(len1,len2);
	printf("%d",dp[len1][len2]);
	return 0;
}
原文地址:https://www.cnblogs.com/-pwl/p/13730763.html