java版AC自动机

时间:2022-04-30 22:04:07
 class Trie
{
int [][]Next=new int[500005][128];
int []fail=new int[500005];
int []end=new int[500005];
int root, L;
int newnode()
{
for(int i=0;i<128;i++)
Next[L][i]=-1;
end[L++]=0;
return L-1;
}
void init()
{
L=0;
root=newnode();
}
void insert(byte buf[], int id)
{
int now=root;
for(int i=0; i<buf.length; i++)
{
if(Next[now][buf[i]]==-1)
Next[now][buf[i]]=newnode();
now=Next[now][buf[i]];
}
end[now]=id;
}
void build()
{
Queue<Integer> q=new LinkedList<Integer>();
fail[root]=root;
for(int i=0; i<128; i++)
{
if(Next[root][i]==-1)
Next[root][i]=root;
else
{
fail[Next[root][i]]=root;
q.add(Next[root][i]);
}
}
while(!q.isEmpty())
{
int now=q.poll();
for(int i=0; i<128; i++)
{
if(Next[now][i]==-1)
Next[now][i]=Next[fail[now]][i];
else
{
fail[Next[now][i]]=Next[fail[now]][i];
q.add(Next[now][i]);
}
}
}
}
int query(byte buf[], int n, String s[])
{
int now=root;
int ans=0;
for(int i=0; i<buf.length; i++)
{
now=Next[now][buf[i]];
int temp=now;
while(temp!=root)
{
ans+=end[temp];
end[temp]=0;
temp=fail[temp];
}
}
return ans;
}
}