Input
Output
Sample Input7 3 SNNSSNS NNSS NNN WSEE
Sample Output4 2 0Hint
对于100%的数据,N<=10^7,M<=10^5,每一段文字的长度<=100。
应上传者要求,此题不公开,如有异议,请提出.
思路:AC自动机,一开始以为不能一直沿着Fail指针上传,会TLE,需要优化。但其实每个点最多标记一次,所以整体复杂度是O(Lc+Ls)的。
所以暴力搞就行了。
#include<bits/stdc++.h> using namespace std; const int maxn=10000010; char c[maxn],s[maxn]; int ch[maxn][4],fa[maxn],pos[maxn],vis[maxn]; int q[maxn],dep[maxn],fail[maxn],cnt,head,tail; int get(char chr){ if(chr=='E') return 0; if(chr=='S') return 1; if(chr=='W') return 2; return 3;} void insert(int opt) { int Now=0,d=0; for(int i=1;c[i];i++){ d++; if(!ch[Now][get(c[i])]) { ch[Now][get(c[i])]=++cnt; fa[cnt]=Now; dep[cnt]=d; } Now=ch[Now][get(c[i])]; } pos[opt]=Now; } void failbuild() { for(int i=0;i<4;i++) if(ch[0][i]) q[++head]=ch[0][i]; while(tail<head){ int Now=q[++tail]; for(int i=0;i<4;i++){ if(ch[Now][i]) { fail[ch[Now][i]]=ch[fail[Now]][i]; q[++head]=ch[Now][i]; } else ch[Now][i]=ch[fail[Now]][i]; } } } int main() { int L,N,i,j; scanf("%d%d%s",&L,&N,s+1); for(i=1;i<=N;i++){ scanf("%s",c+1); insert(i); } failbuild(); int Now=0; for(i=1;i<=L;i++){ Now=ch[Now][get(s[i])]; int tmp=Now; while(tmp&&!vis[tmp]){ vis[tmp]=1; tmp=fail[tmp]; } } for(i=1;i<=N;i++){ Now=pos[i]; while(!vis[Now]&&Now) Now=fa[Now]; printf("%d\n",dep[Now]); } return 0; }
















