最长公共子序列

原理

见《进阶指南》第264页。

模板题

Aizu-ALDS1_10_C-Longest Common Subsequenceopen in new window

#include <iostream>
#include <cstring>
using namespace std;

const int N = 1010;
char a[N], b[N];
int f[N][N];

int main () {
    int T;
    scanf("%d", &T);
    while (T --) {
        scanf("%s%s", a + 1, b + 1);
        int n = strlen(a + 1), m = strlen(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][j], f[i - 1][j - 1] + 1);
            }
        }
        printf("%d\n", f[n][m]);
    }
    return 0;
}
最后修改于: