#include using namespace std; #define rep(i, a, b) for(int i=a; i pii; typedef pair pll; typedef vector vi; typedef vector vll; vector dp; vector jmp; vector true_jmp; vector> allowed, ran; vector par, letter; int n, m0; string s, r; int run(int a, int b) { if (a == 0 && b == 0) return 0; if (a <= -1 || b <= -1) return -10000; if (ran[a][b]) return dp[a][b]; ran[a][b] = true; int res = run(a-1, b); if (b >= 1 && true_jmp[b-1] != -1) { res = max(res, run(a, true_jmp[b-1])); } if (a >= 1 && b >= 1 && allowed[b-1][s[a-1]-'a']) { res = max(res, run(a-1, b-1)+1); } if (b >= 1 && par[b-1]) res = max(res, run(a, b-1)); dp[a][b] = res; cout << a << " " << b << " " << dp[a][b] << endl; return res; } int main() { cin.tie(0)->sync_with_stdio(0); cin.exceptions(cin.failbit); cin >> n >> s >> m0 >> r; vector stack; int m = 0; for (int i=0; i(26, false)); if (r[i] == '(') { stack.push_back(m); par[m] = true; } else if (r[i] == ')') { jmp[m] = stack.back(); stack.pop_back(); par[m] = true; } else if (r[i] == '[') { while (r[++i] != ']') { allowed[m][r[i] - 'a'] = true; } letter[m] = true; } else if (r[i] == '?') { for (int i=0; i<26; i++) { allowed[m][i] = true; } letter[m] = true; } else if (r[i] == '*') { true_jmp[m] = jmp[m-1]; true_jmp[jmp[m-1]] = m; par[m] = true; } else { allowed[m][r[i] - 'a'] = true; letter[m] = true; } m++; } dp.resize(n+1, vi(m+1, -100000)); ran.resize(n+1, vector(m+1)); run(n, m); cout << max(-1, dp[n][m]) << endl; }