P5231 [JSOI2012] 玄武密码
题意
给一个长度为 \(n\) 的字符串 \(s\),和 \(m\) 个串 \(t\),求每个 \(t\) 在 \(s\) 中最长的前缀。
\(n\le10^7,m\le10^5,|t|\le100\)。
思路
把所有 \(t_i\) 丢进 \(ACAM\),对 \(s\) 做一边匹配,把经过的点标记,对于每个 \(t_i\),找祂被标记的节点中最深的那个点。
代码
#include<bits/stdc++.h>
using namespace std;
namespace IO{
template<typename T>
inline void read(T&x){
x=0;char c=getchar();bool f=0;
while(!isdigit(c)) c=='-'?f=1:0,c=getchar();
while(isdigit(c)) x=x*10+c-'0',c=getchar();
f?x=-x:0;
}
template<typename T>
inline void write(T x){
if(x==0){putchar('0');return ;}
x<0?x=-x,putchar('-'):0;short st[50],top=0;
while(x) st[++top]=x%10,x/=10;
while(top) putchar(st[top--]+'0');
}
inline void read(char&c){c=getchar();while(isspace(c)) c=getchar();}
inline void write(char c){putchar(c);}
inline void read(string&s){s.clear();char c;read(c);while(!isspace(c)&&~c) s+=c,c=getchar();}
inline void write(string s){for(int i=0,len=s.size();i<len;i++) putchar(s[i]);}
template<typename T>inline void write(T*x){while(*x) putchar(*(x++));}
template<typename T,typename...T2> inline void read(T&x,T2&...y){read(x),read(y...);}
template<typename T,typename...T2> inline void write(const T x,const T2...y){write(x),putchar(' '),write(y...),sizeof...(y)==1?putchar('\n'):0;}
}using namespace IO;
const int maxn=10000010,maxm=100010,maxlen=10000010;
int bh[200];
class ACAM{
protected:
struct Trie{
int ch[4],fail;
}a[maxlen];
int rt=0,cnt=0,d[maxn];
bool flag[maxlen];
public:
void insert(string s){
int u=rt;
for(int i=0,len=s.size();i<len;i++){
if(a[u].ch[bh[s[i]]]==0) a[u].ch[bh[s[i]]]=++cnt;
u=a[u].ch[bh[s[i]]];
}
}
void build(){
queue<int>q;
for(int i=0;i<4;i++) if(a[rt].ch[i]) q.push(a[rt].ch[i]);
while(!q.empty()){
int u=q.front();
q.pop();
for(int i=0;i<4;i++){
int v=a[u].ch[i];
if(v) a[v].fail=a[a[u].fail].ch[i],d[a[a[u].fail].ch[i]]++,q.push(v);
else a[u].ch[i]=a[a[u].fail].ch[i];
}
}
}
void work(string s){
int u=0;
for(int i=0,len=s.size();i<len;i++){
u=a[u].ch[bh[s[i]]];
flag[u]=1;
}
queue<int>q;
for(int i=1;i<=cnt;i++) if(d[i]==0) q.push(i);
while(!q.empty()){
int u=q.front();
q.pop();
if(--d[a[u].fail]==0) q.push(a[u].fail);
flag[a[u].fail]=max(flag[a[u].fail],flag[u]);
}
}
int calc(string s){
int u=rt,ans=0;
for(int i=0,len=s.size();i<len;i++){
u=a[u].ch[bh[s[i]]];
if(flag[u]) ans=i+1;
}
return ans;
}
}ac;
int n,m;
string s,t[maxm];
signed main(){
bh['E']=0,bh['S']=1,bh['W']=2,bh['N']=3;
read(n,m,s);
for(int i=1;i<=m;i++) read(t[i]),ac.insert(t[i]);
ac.build();
ac.work(s);
for(int i=1;i<=m;i++,write('\n')) write(ac.calc(t[i]));
return 0;
}

浙公网安备 33010602011771号