Subject address:
https://www.acwing.com/problem/content/899/
Given two lengths are NNN andMMM 's stringAAA andBBB , seeking to be bothAAThe subsequence of A isBB againWhat is the longest string length of the subsequence of B ?
Data range:
1 ≤ N, M ≤ 1000 1\le N,M\le 10001≤N,M≤1000
The idea is dynamic programming. Let f [i] [j] f[i][j]f [ i ] [ j ] YesAAA basis beforeiii characters andBBB 's formerjjThe length of the longest common subsequence of j characters. WhenA [i] ≠ B [j] A[i]\ne B[j]A[i]=When B [ j ] , obviouslyf [i] [j] = max {f [i − 1] [j], f [i] [j − 1]} f[i][j]=\max\ {f[i-1][j],f[i][j-1]\}f[i][j]=max{ f[i−1][j],f[i][j−1]};当 A [ i ] = B [ j ] A[i]=B[j] A[i]=B [ j ] target timef [i] [j] = 1 + f [i − 1] [j − 1] f [i] [j] = 1 + f [i-1] [j-1]f[i][j]=1+f[i−1][j−1 ] , the reason is, first of all it is obvious thatf [i] [j] ≥ 1 + f [i − 1] [j − 1] f[i][j]\ge 1+f[i-1][j-1 ]f[i][j]≥1+f[i−1][j−1 ] and secondly, iff [i] [j]> 1 + f [i − 1] [j − 1] f[i][j]> 1+f[i-1][j-1]f[i][j]>1+f[i−1][j−1 ] , iff [i] [j] f[i][j]f [ i ] [ j ] The last equivalent character isA [i] A[i]A [ i ] sumB [j] B [j]B [ j ], 那么f [i] [j] = 1 + f [i - 1] [j - 1] f [i] [j] = 1 + f [i-1] [j-1]f[i][j]=1+f[i−1][j−1 ] , contradiction; if not, thenf [i] [j] = max {f [i − 1] [j], f [i] [j − 1]} f[i][j]=\ max\{f[i-1][j],f[i][j-1]\}f[i][j]=max{ f[i−1][j],f[i][j−1]},如果是 f [ i − 1 ] [ j ] > 1 + f [ i − 1 ] [ j − 1 ] f[i-1][j]>1+f[i-1][j-1] f[i−1][j]>1+f[i−1][j−1 ] , also considerf [i − 1] [j] f[i-1][j]f[i−1 ] The last character of [ j ] , ift [j] t[j] is usedt[j]就会得出 1 + f [ i − 1 ] [ j − 1 ] > 1 + f [ i − 1 ] [ j − 1 ] 1+f[i-1][j-1]>1+f[i-1][j-1] 1+f[i−1][j−1]>1+f[i−1][j−1 ] contradiction; if it is not used,f [i − 1] [j − 1]> 1 + f [i − 1] [j − 1] f[i-1][j-1]> 1+f[i-1][j-1]f[i−1][j−1]>1+f[i−1][j−1 ] Also contradictory. Sof [i] [j] = 1 + f [i − 1] [j − 1] f[i][j]=1+f[i-1][j-1]f[i][j]=1+f[i−1][j−1 ] . code show as below:
#include <iostream>
using namespace std;
const int N = 1010;
string s, t;
int n, m;
int f[N][N];
int main() {
cin >> n >> m;
cin >> s >> t;
s = ' ' + s;
t = ' ' + t;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
if (s[i] == t[j]) f[i][j] = 1 + f[i - 1][j - 1];
else f[i][j] = max(f[i - 1][j], f[i][j - 1]);
cout << f[n][m] << endl;
return 0;
}
Time and space complexity O (NM) O(NM)O(NM)。