dp_基础_最长公共子序列

非常经典的一道题
设dp[i][j]为最长公共子序列
i:s1以i为结尾的字符串 j:s2以i为结尾的字符串
则有
无后效性:i+1与j+1 不会影响之前的
子问题重叠:使用i-1, j-1 来代表已经对的结果
最优子结构:dp[i][j] = s[i-1] == s[j-1] ? dp[i-1][j-1] + 1 : max(dp[i-1][j],dp[i][j-1]);


如图所示


http://poj.org/problem?id=1458 ac答案

int calc(const char* s1,const char* s2){
	int l1 = strlen(s1);
	int l2 = strlen(s2);
	vector<vector<int>> dp(l1+1,vector<int>(l2+1));
	for( int i=1;i<=l1;i++ ){
		for( int j=1;j<=l2;++j ){
			if ( s1[i-1] == s2[j-1] ){
				dp[i][j] = dp[i-1][j-1] + 1;
			}else{
				dp[i][j] = max(dp[i-1][j],dp[i][j-1]);
			}
		}
	}
	return dp[l1][l2];
}

int main(){
	string s1,s2;
	while(cin >> s1 >> s2){
		cout << calc(s1.c_str(),s2.c_str()) << "\n";
	}
	return 0;
}
posted @ 2022-05-06 13:26  传说中的水牛  阅读(19)  评论(0编辑  收藏  举报