#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 parentheses_open; ll pos = 0; while(pos < m){ char znak = regex[pos]; if(znak == '?'){ last_state++; For(i,1,27){ prechody[i].push_back({last_state-1,last_state}); } }else if(znak == '['){ pos++; last_state++; while(regex[pos] != ']'){ prechody[regex[pos]-'a'+1].push_back({last_state-1,last_state}); pos++; } }else if(znak == '*'){ last_state++; prechody[0].push_back({last_state-1,last_state-2}); prechody[0].push_back({last_state-2,last_state}); }else if(znak == '('){ parentheses_open = last_state; last_state++; prechody[0].push_back({last_state-1,last_state}); }else if(znak == ')'){ pos++; if(pos == m || regex[pos] != '*'){ last_state++; prechody[0].push_back({last_state-1,last_state}); }else{ prechody[0].push_back({last_state,parentheses_open}); last_state++; prechody[0].push_back({parentheses_open,last_state}); } }else{ last_state++; prechody[znak-'a'+1].push_back({last_state-1,last_state}); } pos++; } vector dynamic(last_state+1); dynamic[0] = 0; For(i,1,last_state+1){ dynamic[i] = -1; } while(true){ bool changed = false; For(j,0,prechody[0].size()){ pii prechod = prechody[0][j]; if(dynamic[prechod.first]>dynamic[prechod.second]){ changed = true; dynamic[prechod.second] = dynamic[prechod.first]; } } if(!changed){ break; } } dbg(dynamic); 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]; if(dynamic[prechod.first] == -1){ nove.push_back(-1); }else{ nove.push_back(dynamic[prechod.first]+1); } } For(j,0,prechody[index].size()){ pii prechod = prechody[index][j]; dynamic[prechod.second] = max(nove[j],dynamic[prechod.second]); } while(true){ bool changed = false; For(j,0,prechody[0].size()){ pii prechod = prechody[0][j]; if(dynamic[prechod.first]>dynamic[prechod.second]){ changed = true; dynamic[prechod.second] = dynamic[prechod.first]; } } if(!changed){ break; } } dbg(dynamic); dbg(parentheses_open); dbg(prechody[0]); } 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(); } }