#include <bits/stdc++.h> using namespace std; const int N = 3000 + 5; bool match[N][N]; int dp[N][N]; void solve(int i, int j, int k, int l) { for (int a = i - 1; a <= j; a++) { dp[a][k - 1] = 0; } for (int b = k - 1; b <= l; b++) { dp[i - 1][b] = 0; } for (int a = i; a <= j; a++) { for (int b = k; b <= l; b++) { if (match[a][b]) { dp[a][b] = 1 + dp[a - 1][b - 1]; } else { dp[a][b] = max(dp[a - 1][b], dp[a][b - 1]); } } } cout << dp[j][l] << "\n"; } int main() { ios_base::sync_with_stdio(false); int n, m, q; cin >> n >> m >> q; string s, t; cin >> s >> t; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { match[i][j] = (s[i - 1] == t[j - 1]); } } while (q--) { int i, j, k, l; cin >> i >> j >> k >> l; solve(i, j, k, l); } }
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 | #include <bits/stdc++.h> using namespace std; const int N = 3000 + 5; bool match[N][N]; int dp[N][N]; void solve(int i, int j, int k, int l) { for (int a = i - 1; a <= j; a++) { dp[a][k - 1] = 0; } for (int b = k - 1; b <= l; b++) { dp[i - 1][b] = 0; } for (int a = i; a <= j; a++) { for (int b = k; b <= l; b++) { if (match[a][b]) { dp[a][b] = 1 + dp[a - 1][b - 1]; } else { dp[a][b] = max(dp[a - 1][b], dp[a][b - 1]); } } } cout << dp[j][l] << "\n"; } int main() { ios_base::sync_with_stdio(false); int n, m, q; cin >> n >> m >> q; string s, t; cin >> s >> t; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { match[i][j] = (s[i - 1] == t[j - 1]); } } while (q--) { int i, j, k, l; cin >> i >> j >> k >> l; solve(i, j, k, l); } } |