#include <cstdio> #include <cstring> #include <algorithm> using namespace std; int L[3001][3001]; char s[3001], t[3001]; int lcs(char *x, char *y, int n, int m) { for (int i = 0; i <= n; i++) L[i][0] = 0; for (int j = 0; j <= m; j++) L[0][j] = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (x[i] == y[j]) { L[i + 1][j + 1] = 1 + L[i][j]; } else { int a = L[i + 1][j], b = L[i][j + 1]; if (a > b) { L[i + 1][j + 1] = a; } else { L[i + 1][j + 1] = b; } } } } return L[n][m]; } int main() { int n, m, q; scanf("%d %d %d", &n, &m, &q); scanf("%s", s); scanf("%s", t); for (int z = 0; z < q; z++) { int i, j, k, l; scanf("%d %d %d %d", &i, &j, &k, &l); --i, --j, --k, --l; int ret = lcs(s + i, t + k, j - i + 1, l - k + 1); printf("%d\n", ret); } return 0; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | #include <cstdio> #include <cstring> #include <algorithm> using namespace std; int L[3001][3001]; char s[3001], t[3001]; int lcs(char *x, char *y, int n, int m) { for (int i = 0; i <= n; i++) L[i][0] = 0; for (int j = 0; j <= m; j++) L[0][j] = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (x[i] == y[j]) { L[i + 1][j + 1] = 1 + L[i][j]; } else { int a = L[i + 1][j], b = L[i][j + 1]; if (a > b) { L[i + 1][j + 1] = a; } else { L[i + 1][j + 1] = b; } } } } return L[n][m]; } int main() { int n, m, q; scanf("%d %d %d", &n, &m, &q); scanf("%s", s); scanf("%s", t); for (int z = 0; z < q; z++) { int i, j, k, l; scanf("%d %d %d %d", &i, &j, &k, &l); --i, --j, --k, --l; int ret = lcs(s + i, t + k, j - i + 1, l - k + 1); printf("%d\n", ret); } return 0; } |