#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
static const int N = 1000;
int lcs (string x, string y) {
int m = x.size();
int n = y.size();
int maxl = 0;
int c[N + 1][N + 1] ;
x = ' ' + x; //在前面补个空格 这个操作很秀
y = ' ' + y;
for (int i = 0; i <= m; i++) {
c[i][0] = 0;
}
for (int j = 1; j <= n; j++) {
c[0][j] = 0;
}
for (int i = 1; i <= m; i ++ ) {
for (int j = 1; j <= n; j++) {
if (x[i] == y[j]) { //如果不补空格, 那么这里 i 、j 就要从 0
//开始计数, 导致 c[i-1][j] 溢出
c[i][j] = c[i - 1][j - 1] + 1;
} else {
c[i][j] = max(c[i - 1][j], c[i][j - 1]);
}
maxl = max(maxl, c[i][j]);
}
}
return maxl;
}
int main () {
int n ;
cin >> n;
string str1, str2;
for (int i = 0; i < n; i++) {
cin>>str1>>str2;
cout << lcs(str1, str2) <<endl;
}
return 0;
}
题目地址: https://onlinejudge.u-aizu.ac.jp/courses/lesson/1/ALDS1/10/ALDS1_10_C