0
点赞
收藏
分享

微信扫一扫

Longest Common Subsequence(入门dp题)

原题链接: ​​https://vjudge.net/contest/389452#problem/C​​

Longest Common Subsequence(入门dp题)_dp
测试样例:

Input
abcfbc abfcab
programming contest
abcd mnp
Output
4
2
0
Input
abcfbc abfcab
programming contest
abcd mnp
Output
4
2
0

题意: 给你两个字符串,求它们的最长公共子序列长度。

解题思路: 这道题是一道经典的dp问题,为什么是呢?由于我们是找字符串的公共子序列长度,那么这个问题是不是可以转变为先找字符串1前Longest Common Subsequence(入门dp题)_#define_02个字符和字符串前Longest Common Subsequence(入门dp题)_#define_03个字符的公共子序列长度,再慢慢递进。由此我们也就可以找到一个状态Longest Common Subsequence(入门dp题)_dp_04,它就代表了我们上面所说的那个状态。那么初始状态就是Longest Common Subsequence(入门dp题)_字符串_05Longest Common Subsequence(入门dp题)_字符串_06,这即是我们已经知道的结果。最终状态就是Longest Common Subsequence(入门dp题)_#define_07,我们从初始状态一步一步推到最终状态。OK,具体看代码。

AC代码:

/*
*、
*
*/
#include<bits/stdc++.h> //POJ不支持

#define rep(i,a,n) for (int i=a;i<=n;i++)//i为循环变量,a为初始值,n为界限值,递增
#define per(i,a,n) for (int i=a;i>=n;i--)//i为循环变量, a为初始值,n为界限值,递减。
#define pb push_back
#define IOS ios::sync_with_stdio(false);cin.tie(0); cout.tie(0)
#define fi first
#define se second
#define mp make_pair

using namespace std;

const int inf = 0x3f3f3f3f;//无穷大
const int maxn = 1e3;//最大值。
typedef long long ll;
typedef long double ld;
typedef pair<ll, ll> pll;
typedef pair<int, int> pii;
//*******************************分割线,以上为自定义代码模板***************************************//

string s1,s2;
int dp[maxn][maxn];
int main(){
//freopen("in.txt", "r", stdin);//提交的时候要注释掉
IOS;
while(cin>>s1>>s2){
int len1=s1.size();
int len2=s2.size();
rep(i,0,len1)dp[i][0]=0;
rep(j,0,len2)dp[0][j]=0;
rep(i,1,len1){
rep(j,1,len2){
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]);
}
}
cout<<dp[len1][len2]<<endl;
}
return 0;
}


举报

相关推荐

0 条评论