https://vjudge.net/problem/POJ-1458
A subsequence of a given sequence is the given sequence with some elements (possible none) left out. Given a sequence X = < x1, x2, ..., xm > another sequence Z = < z1, z2, ..., zk > is a subsequence of X if there exists a strictly increasing sequence < i1, i2, ..., ik > of indices of X such that for all j = 1,2,...,k, x ij = zj. For example, Z = < a, b, f, c > is a subsequence of X = < a, b, c, f, b, c > with index sequence < 1, 2, 4, 6 >. Given two sequences X and Y the problem is to find the length of the maximum-length common subsequence of X and Y.
Dp[i][j]表示a的前i位和b的前j位组成的最长长度,如果a[i] = b[j] 则可以从Dp[i-1][j-1]转移而来, 再去Dp[i-1][j] 和Dp[i][j-1]的最大值.
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
//#include <memory.h>
#include <queue>
#include <set>
#include <map>
#include <algorithm>
#include <math.h>
#include <stack>
#include <string>
#include <assert.h>
#include <iomanip>
#include <iostream>
#include <sstream>
#define MINF 0x3f3f3f3f
using namespace std;
typedef long long LL;
const LL MOD = 20090717;
const int MAXN = 1e3+10;
int Dp[MAXN][MAXN];
char a[MAXN], b[MAXN];
int main()
{
while (~scanf("%s%s", a+1, b+1))
{
memset(Dp, 0, sizeof(Dp));
int lena = strlen(a+1), lenb = strlen(b+1);
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;
Dp[i][j] = max(Dp[i][j], max(Dp[i-1][j], Dp[i][j-1]));
}
}
printf("%d\n", Dp[lena][lenb]);
}
return 0;
}
POJ-1458-Common Subsequence(最长公共子序列)
原文:https://www.cnblogs.com/YDDDD/p/11666070.html