O(n²)
#include<iostream> #include<cmath> #include<algorithm> #include<cstdio> #include<vector> #include<queue> #include<string.h> #include<set> #include<map> using namespace std; const int maxn =1e6+10; char a[maxn]; char b[maxn]; int f[1006][1006]; int main() { int n,m; cin >> n >> m; cin >> a+1; cin >> b+1; for(int i=1;i<=n;i++) { for(int j=1;j<=m;j++) { f[i][j]=max(f[i-1][j],f[i][j-1]); if(a[i]==b[j]) f[i][j]=max(f[i-1][j-1]+1,f[i][j]); } } cout << f[n][m] << endl; return 0; }