LCS template
#include <bits/stdc++.h>
using namespace std;
const int N = 1000;
int dp[N][N];
char A[N], B[N];
int main()
{
fgets(A + 1, N, stdin);
fgets(B + 1, N, stdin);
int lenA = strlen(A+1);
int lenB = strlen(B+1);
for(int i = 0; i <= lenA; i++)
{
dp[i][0] = 0;
}
for(int j = 0; j <= lenB; j++)
{
dp[0][j] = 0;
}
for(int i = 1; i <= lenA; i++)
{
for(int j = 1; j <= lenB; j++)
{
if(A[i] == B[j])
{
dp[i][j] = dp[i-1][j-1] + 1;
}
else
{
dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
}
}
}
cout << dp[lenA-1][lenB] << endl;
return 0;
}
Problem solution ideas
This problem can be solved with the longest non-decreasing subsequence
or the longest common subsequence. However, since there can be repeated elements, the equation of state is different from the template and needs to be modified.
if(A[i] == B[j])
{
dp[i][j] = max(dp[i-1][j], dp[i][j-1]) + 1;
}
else
{
dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
}
AC code
#include <bits/stdc++.h>
using namespace std;
const int maxn = 10010;
int A[maxn], B[maxn];
int dp[maxn][maxn];
map<int, int> mp;
int main()
{
int n;
cin >> n;
int m;
cin >> m;
for(int i = 1; i <= m; i++)
{
cin >> A[i];
}
int l;
cin >> l;
for(int j = 1; j <= l; j++)
{
cin >> B[j];
}
for(int i = 0; i <= m; i++)
{
dp[i][0] = 0;
}
for(int j = 0; j <= l; j++)
{
dp[0][j] = 0;
}
for(int i = 1; i <= m; i++) //dp[i][j]存放的是上一步的较大值
{
for(int j = 1; j <= l; j++)
{
if(A[i] == B[j])
{
dp[i][j] = max(dp[i-1][j], dp[i][j-1]) + 1;
}
else
{
dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
}
}
}
cout << dp[m][l];
return 0;
}