# CSES | Finding Patterns

Hi, Can Anyone Please suggest me to where I am making a logical error in my code? The question is CSES Finding Patterns.

I was trying to implement the logic as given in the code forces article, which I feel very convenient way to implement Aho-corasick.

I am failing in two test cases of CSES #12 and #14

``````#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define pb push_back
#define sz(x) x.size()
#define FOR(i,a,b) for(int i=a;i<b;++i)

const int maxN = 5e5+5,sigma = 26;
vector<int> term[maxN];

int cur = 0;
for(auto c:s){
if(!to[cur][c-'a']){
to[cur][c-'a'] = sz++;
len[to[cur][c-'a']] = len[cur]+1;
}
cur = to[cur][c-'a'];
}
term[cur].pb(pos);
}

int que[sz];
int st = 0, fi = 1;
que[0] = 0;
while(st<fi){
int V = que[st++];
if(!sz(term[V]) && V != 0) for(auto x:term[U]) term[V].pb(x);
for(int c = 0;c<sigma;++c){
if(to[V][c]){
que[fi++] = to[V][c];
}
else{
to[V][c] = to[U][c];
}
}
}
}
void bfs(string& txt){
int idx = 0, cur = 0;
while(idx<(int)txt.length()){
if(to[cur][txt[idx]-'a']){
cur = to[cur][txt[idx]-'a'];
++idx;
}
else if(cur){
// cur = to[cur][txt[idx-1]-'a'];
}
else
++idx;
if(sz(term[cur])) {for(auto x:term[cur]) ans[x] = 1; term[cur] = {};}
}

}

int main(){
ios_base::sync_with_stdio(0);
cin.tie(NULL);cout.tie(NULL);

string s;cin>>s;
int q;cin>>q;

for(int i=0;i<q;++i){
string t;cin>>t;
}
bfs(s);
FOR(i,0,q){
if(ans[i]) cout<<"YES"<<'\n';
else cout<<"NO\n";
}
// for(int i=0;i<sz;++i){
//     for(int j=0;j<26;++j)
//         cout<<to[i][j]<<' ';
//     cout<<'\n';
// }
// cout<<'\n';
// for(int i=0;i<sz;++i){
//     if(sz(term[i])) cout<<i<<' ';
// }
// cout<<'\n';
// for(int i=0;i<sz;++i){