Pagini recente » Cod sursa (job #3277517) | Cod sursa (job #2202615) | Cod sursa (job #1968342) | Cod sursa (job #2768312) | Cod sursa (job #2831147)
#include <bits/stdc++.h>
#define NMAX 300000
#define ll long long
#define pb push_back
using namespace std;
ifstream f("ahocorasick.in");
ofstream g("ahocorasick.out");
string a;
char cuv[100005];
struct Trie
{
int cnt;
Trie *fiu[26],*backedge;
vector<Trie*> v;
Trie()
{
cnt=0;
for(int i=0; i<26; i++) fiu[i]=NULL;
backedge=NULL;
v.clear();
}
};
stack<Trie*> stk;
Trie *ans[100005];
Trie *root=new Trie;
Trie *update(Trie *nod, char *s)
{
if(*s<'a'||*s>'z')
{
//nod->cnt++;
return nod;
}
if(nod->fiu[*s-'a']==NULL) nod->fiu[*s-'a']=new Trie;
return update(nod->fiu[*s-'a'],s+1);
}
void bfs()
{
queue< Trie* > q;
q.push(root);
while(!q.empty())
{
Trie *nod= q.front();
q.pop();
stk.push(nod);
for(int i=0; i<26; i++)
{
if(nod->fiu[i]!=NULL)
{
Trie *bk= nod->backedge;
while(bk!=NULL&&bk->fiu[i]==NULL)
{
bk=bk->backedge;
}
if(bk==NULL) bk=root;
else bk=bk->fiu[i];
nod->fiu[i]->backedge=bk;
//bk->v.push_back(nod->fiu[i]);
q.push(nod->fiu[i]);
}
}
}
}
void matchwords(string s)
{
Trie* node = root;
for(char c: s)
{
while(node!=NULL&&node->fiu[c-'a']==NULL)
{
node=node->backedge;
}
if(node==NULL) node=root;
else node=node->fiu[c-'a'];
node->cnt++;
}
}
void solve()
{
while(!stk.empty())
{
Trie *node=stk.top();
stk.pop();
if(node->backedge!=NULL)
{
node->backedge->cnt+=node->cnt;
}
}
}
int main()
{
f>>a;
int n;
f>>n;
for(int i=1;i<=n;i++)
{
f>>cuv;
ans[i]=update(root,cuv);
}
bfs();
matchwords(a);
solve();
for(int i=1;i<=n;i++)
{
g<<ans[i]->cnt<<'\n';
}
}