没开动态数组,没用递归栈,数组只开到2e7不到,MLE了九个点。
#include<bits/stdc++.h>
using namespace std;
const int N=2605,M=1e5+5;
int ch[N][4],n,m,idx;
int dep[N],ne[N],vis[N];
string s1,s2[M];
int change(char x){
if(x=='S') return 0;
else if(x=='N') return 1;
else if(x=='W') return 2;
else return 3;
}
void insert(int x){
int u=0,len=s2[x].size();
for(int i=0;i<len;i++){
int j=change(s2[x][i]);
if(ch[u][j]==0) ch[u][j]=++idx;
int v=ch[u][j];
dep[v]=dep[u]+1;
u=v;
}
}
int ans[M];
void query1(){
int len=s1.size();
for(int k=0,i=0;k<len;k++){
i=ch[i][change(s1[k])];
for(int j=i;j;j=ne[j]){
vis[j]+=1;//为文本串可能的字串打上标记
}
}
}
int query2(string s){
int u=0,len=s.size();
for(int i=0;i<len;i++){
int j=change(s[i]);
int v=ch[u][j];
if(vis[v]){//是文本串的字串
u=ch[u][j];
}else{
return dep[u];//不是,结束匹配
}
}
}
void build(){
queue<int> q;
for(int i=0;i<4;i++)
if(ch[0][i]) q.push(ch[0][i]);
while(!q.empty()){
int u=q.front();q.pop();
for(int i=0;i<4;i++){
int v=ch[u][i];
if(v){
ne[v]=ch[ne[u]][i];
q.push(v);
}else{
ch[u][i]=ch[ne[u]][i];
}
}
}
}
signed main(){
ios::sync_with_stdio(false);
cin.tie(0);
cin>>n>>m;
cin>>s1;
for(int i=1;i<=m;i++){
cin>>s2[i];
insert(i);
}
build();
query1();
for(int i=1;i<=m;i++){
cout<<query2(s2[i])<<endl;
}
return 0;
}