Pagini recente » Cod sursa (job #3191591) | Cod sursa (job #2938656) | Istoria paginii utilizator/burgundyshadow | Cod sursa (job #2476883) | Cod sursa (job #2391679)
#include <bits/stdc++.h>
using namespace std;
ifstream fin ("ahocorasick.in");
ofstream fout ("ahocorasick.out");
struct nod{
vector<nod*>phi;
nod *vec[26], *last;
int nr;
nod () {
nr = 0;
last =0;
memset(vec, 0, sizeof(vec));
}
};
nod *root;
nod *poz[102];
nod* baga (string s) {
nod *t = root;
string ch;
for (int i = 0; i < s.size(); i++) {
ch += s[i];
if (t -> vec[s[i] - 'a'] == 0)
t -> vec[s[i] - 'a'] = new nod;
t = t -> vec[s[i] - 'a'];
}
return t;
}
void dfs (nod *x) {
for (auto it : x->phi) {
dfs(it);
x -> nr += it -> nr;
}
}
string a, s;
int n;
int main()
{
fin >> a >> n;
root = new nod;
for (int i = 1; i <= n; i++) {
fin >> s;
poz[i] = baga(s);
}
queue<nod*>q;
q.push(root);
while (!q.empty()) {
nod *u = q.front();
q.pop();
for (int i = 0; i < 26; i++) {
if (u -> vec[i] == NULL)
continue;
nod *aux = u -> last;
while (aux != NULL && aux -> vec[i] == NULL)
aux = aux -> last;
if (aux == NULL)
u -> vec[i] -> last = root;
else
u -> vec[i] -> last = aux -> vec[i];
u -> vec[i] -> last -> phi.push_back(u -> vec[i]);
q.push(u -> vec[i]);
}
}
nod *aux = root;
for(int i = 0; i < a.size(); i++){
while(aux != NULL && aux -> vec[a[i] - 'a'] == NULL)
aux = aux -> last;
if(aux == NULL)
aux = root;
if (aux -> vec[a[i] - 'a'] != NULL){
aux -> vec[a[i] - 'a'] -> nr++;
aux = aux -> vec[a[i] - 'a'];
}
}
dfs(root);
for (int i = 1; i <= n; i++)
fout << poz[i] -> nr << "\n";
return 0;
}