#include <bits/stdc++.h> using namespace std; string AA, BB; string A, B; int dp[609][609]; int LCS(int a, int b) { if(dp[a][b] >= 0) return dp[a][b]; if(a==0 or b==0) return 0; if(A[a-1] == B[b-1]) dp[a][b] = LCS(a-1, b-1) + 1; else dp[a][b] = max(LCS(a-1, b), LCS(a, b-1)); return dp[a][b]; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n, m, q; cin >> n >> m >> q; cin >> AA >> BB; while(q--) { for(int i=0;i<609;i++) for(int j=0;j<609;j++) dp[i][j] = -1; int a, b, c, d; cin >> a >> b >> c >> d; string first = AA.substr(a-1, b-a+1); string second = BB.substr(c-1, d-c+1); A = first; B = second; cout << LCS(A.size(), B.size()) << "\n"; } }
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 | #include <bits/stdc++.h> using namespace std; string AA, BB; string A, B; int dp[609][609]; int LCS(int a, int b) { if(dp[a][b] >= 0) return dp[a][b]; if(a==0 or b==0) return 0; if(A[a-1] == B[b-1]) dp[a][b] = LCS(a-1, b-1) + 1; else dp[a][b] = max(LCS(a-1, b), LCS(a, b-1)); return dp[a][b]; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n, m, q; cin >> n >> m >> q; cin >> AA >> BB; while(q--) { for(int i=0;i<609;i++) for(int j=0;j<609;j++) dp[i][j] = -1; int a, b, c, d; cin >> a >> b >> c >> d; string first = AA.substr(a-1, b-a+1); string second = BB.substr(c-1, d-c+1); A = first; B = second; cout << LCS(A.size(), B.size()) << "\n"; } } |