#include using namespace std; #define For(i, a, n) for(int i =a;i pii; template void dbg(Args&&... args){ ((cerr< pair operator+(const pair&a, const pair& b){ return {a.first +b.first, a.second + b.second}; } template ostream& operator<< (ostream& os, const pair& a){ return os<<"("< basic_ostream& operator<<(basic_ostream& os, const C&c){ for(auto it=begin(c); it!=end(c);++it){ os<<(it==begin(c)?"":" ")<<*it; } return os; } void solve(){ ll n,m; cin >> n; string eggs; cin >> eggs; cin >> m; string regex; cin >> regex; vector> prechody(27); ll last_state = 0; ll states_needed = 1; ll old_state; ll very_old; ll pos = 0; while(pos < m){ char znak = regex[pos]; if(znak == '?'){ old_state = last_state; last_state = states_needed; states_needed++; For(i,1,27){ prechody[i].push_back(pii(old_state,last_state)); } }else if(znak == '['){ pos++; old_state = last_state; last_state = states_needed; states_needed++; while(regex[pos] != ']'){ prechody[regex[pos]-'a'+1].push_back(pii(old_state,last_state)); pos++; } }else if(znak == '*'){ prechody[0].push_back(pii(last_state,old_state)); last_state = old_state; old_state = last_state; last_state = states_needed; states_needed++; prechody[0].push_back(pii(old_state,last_state)); }else if(znak == '('){ very_old = last_state; }else if(znak == ')'){ pos++; prechody[0].push_back(pii(last_state,very_old)); last_state = very_old; old_state = last_state; last_state = states_needed; states_needed++; prechody[0].push_back(pii(old_state,last_state)); }else{ old_state = last_state; last_state = states_needed; states_needed++; prechody[znak-'a'+1].push_back(pii(old_state,last_state)); } pos++; } vector dynamic(states_needed); dynamic[0] = 0; For(i,1,states_needed){ dynamic[i] = -1; } For(j,0,prechody[0].size()){ pii prechod = prechody[0][j]; dynamic[prechod.second] = max(dynamic[prechod.first],dynamic[prechod.second]); } For(i,0,n){ char znak = eggs[i]; ll index = znak-'a'+1; vector nove; For(j,0,prechody[index].size()){ pii prechod = prechody[index][j]; nove.push_back(max(dynamic[prechod.first]+1,dynamic[prechod.second])); } For(j,0,prechody[index].size()){ pii prechod = prechody[index][j]; dynamic[prechod.second] = max(nove[j],dynamic[prechod.second]); } For(j,0,prechody[0].size()){ pii prechod = prechody[0][j]; dynamic[prechod.second] = max(dynamic[prechod.first],dynamic[prechod.second]); } } cout << dynamic[last_state] << "\n"; } main(){ cin.tie(0)->sync_with_stdio(0); cin.exceptions(cin.failbit); int t=1;//cin>>t; while(t--){ solve(); } }