Pagini recente » Cod sursa (job #2284941) | Cod sursa (job #1834115) | Cod sursa (job #1357656) | Cod sursa (job #2829779) | Cod sursa (job #3190607)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("ahocorasick.in");
ofstream fout("ahocorasick.out");
char s[1000005];
char s2[10005];
struct trie{
int next[26];
bool terminal;
int t, suf, ap;
vector <int> idx;
char ch;
trie(){
terminal = 0;
t = ap = suf = 0;
memset(next, -1, sizeof next);
}
};
vector <trie> v;
void add_string(char *ch, int id){
int nod = 0;
while(*ch != '\0'){
if(v[nod].next[*ch - 'a'] == -1){
v.push_back(trie());
int new_nod = v.size() - 1;
v[nod].next[*ch - 'a'] = new_nod;
v[new_nod].ch = *ch;
v[new_nod].t = nod;
nod = new_nod;
}
else nod = v[nod].next[*ch - 'a'];
ch++;
}
v[nod].terminal = 1;
v[nod].idx.push_back(id);
}
queue <int> q;
stack <int> st;
void build(){
q.push(0);
st.push(0);
while(!q.empty()){
for(int i = 0; i < 26; i++){
if(v[q.front()].next[i] != -1){
int e = v[q.front()].suf;
while(e && v[e].next[i] == -1) e = v[e].suf;
if(v[e].next[i] != -1 && v[e].next[i] != v[q.front()].next[i]) e = v[e].next[i];
v[v[q.front()].next[i]].suf = e;
q.push(v[q.front()].next[i]);
st.push(q.back());
}
}
q.pop();
}
}
void calc_ap(){
while(!st.empty()){
if(v[st.top()].suf != -1) v[v[st.top()].suf].ap += v[st.top()].ap;
st.pop();
}
}
int nrap[102];
int main()
{
int n,i,m,nod = 0,st = 0;
v.push_back(trie());
fin >> s;
fin >> m;
for(i = 1; i <= m; i++){
fin.get();
fin >> s2;
add_string(s2,i);
}
build();
n = strlen(s);
for(i = 0; i < n; i++){
int nxt = s[i] - 97;
while(v[nod].next[nxt] == -1 && nod) nod = v[nod].suf;
if(v[nod].next[nxt] != -1) nod = v[nod].next[nxt];
v[nod].ap++;
}
calc_ap();
for(auto x : v) if(x.terminal){
for(auto x2 : x.idx) nrap[x2] += x.ap;
}
for(i = 1; i <= m; i++) fout << nrap[i] << "\n";
return 0;
}