- Publicado en
A Bonus Classic DP
Common Child
sourceOh, the classic LCS.
Let and be the first and second strings and represent the -th character in string, we can define our recursive solution as follows:
In other words, if we look at the last characters of both strings we have only three possibilities:
- The characters match, so we can add 1 to our answer and remove them both.
- We remove the last character from and look for the LCS of and .
- We remove the last character from and look for the LCS of and .
The rest is simply a matter of implementing the bottom-up solution.
Note: I tried submitting a memoized recursive solution afterwards but it TLE'd in a couple of cases#include<bits/stdc++.h>
using namespace std;
#define N 5010
#define max(x,y) x >= y ? x : y
int dp[N][N];
int main(){
ios::sync_with_stdio(false);
string s,t;
cin >> s >> t;
int n = (int)s.length();
for(int i = 1; i <= n; i++){
for(int j = 1; j <= n; j++){
if(s[i-1] == t[j-1])
dp[i][j] = dp[i-1][j-1] + 1;
else dp[i][j] = max(dp[i][j-1], dp[i-1][j]);
}
}
cout << dp[n][n] << endl;
return 0;
}