title
简化题意:
给定一个长度为 \(N\) 的母串,求 \(M\) 个字符串其前缀在母串上的最大匹配长度。
analysis
先构建 \(Trie\) 树,在查找的时候利用 \(ACAM\) 的性质,记录下每个子串在母串中最远匹配到哪里,就是其最大匹配长度了,比较裸。
code
#include<bits/stdc++.h>
const int maxn=1e7+10,maxm=1e5+10;
namespace IO
{
char buf[1<<15],*fs,*ft;
inline char getc() { return (ft==fs&&(ft=(fs=buf)+fread(buf,1,1<<15,stdin),ft==fs))?0:*fs++; }
template<typename T>inline void read(T &x)
{
x=0;
T f=1, ch=getchar();
while (!isdigit(ch) && ch^'-') ch=getchar();
if (ch=='-') f=-1, ch=getchar();
while (isdigit(ch)) x=(x<<1)+(x<<3)+(ch^48), ch=getchar();
x*=f;
}
char Out[1<<24],*fe=Out;
inline void flush() { fwrite(Out,1,fe-Out,stdout); fe=Out; }
template<typename T>inline void write(T x,char str)
{
if (!x) *fe++=48;
if (x<0) *fe++='-', x=-x;
T num=0, ch[20];
while (x) ch[++num]=x%10+48, x/=10;
while (num) *fe++=ch[num--];
*fe++=str;
}
}
using IO::read;
using IO::write;
struct Aho_Corasick_AutoMaton
{
int son[maxn][4],fail[maxn];
int pos[maxn],cnt;
inline int trans(char s)
{
if (s=='W') return 0;
if (s=='E') return 1;
if (s=='S') return 2;
if (s=='N') return 3;
}
inline void add(char *s)
{
int len=strlen(s+1), now=0;
for (int i=1; i<=len; ++i)
{
int c=trans(s[i]);
if (!son[now][c]) son[now][c]=++cnt;
now=son[now][c];
}
}
inline void build()
{
std::queue<int>q;
for (int i=0; i<4; ++i)
if (son[0][i]) q.push(son[0][i]);
while (!q.empty())
{
int x=q.front();
q.pop();
for (int i=0; i<4; ++i)
if (son[x][i]) fail[son[x][i]]=son[fail[x]][i], q.push(son[x][i]);
else son[x][i]=son[fail[x]][i];
}
}
inline void match(char *s)
{
int len=strlen(s+1), now=0;
for (int i=1; i<=len; ++i)
{
int c=trans(s[i]);
now=son[now][c];
for (int j=now; j; j=fail[j])
{
if (pos[j]) break;
pos[j]=1;
}
}
}
inline int query(char *s)
{
int len=strlen(s+1), now=0, ans=0;
for (int i=1; i<=len; ++i)
{
int c=trans(s[i]);
now=son[now][c];
if (pos[now]) ans=i;
}
return ans;
}
} ACAM;
char ch[maxn],s[maxm][105];
int main()
{
int n,m;read(n);read(m);
scanf("%s",ch+1);
for (int i=1; i<=m; ++i) scanf("%s",s[i]+1), ACAM.add(s[i]);
ACAM.build();
ACAM.match(ch);
for (int i=1; i<=m; ++i) write(ACAM.query(s[i]),'\n');
IO::flush();
return 0;
}