Pagini recente » Cod sursa (job #2339245) | Cod sursa (job #2846526) | Cod sursa (job #290928) | Cod sursa (job #3166090) | Cod sursa (job #2723187)
#include <bits/stdc++.h>
using namespace std;
string s;
struct node {
node* k[26];
node* to;
vector<int> ind;
int cnt;
node() {
for (int j = 0; j < 26; j++) {
k[j] = 0;
}
cnt = 0;
to = 0;
}
};
node* root = new node;
vector<node*> ord;
void bfs() {
queue<node*> q;
q.push(root);
while (!q.empty()) {
node *now = q.front();
ord.push_back(now);
q.pop();
for (int j = 0; j < 26; j++) {
if (now->k[j]) {
q.push(now->k[j]);
}
}
}
}
void build(vector<string> v) {
int y = (int) v.size();
int pz = 0;
for (auto &s : v) {
node* now = root;
for (auto &ch : s) {
int x = ch - 'a';
if (!now->k[x]) {
now->k[x] = new node;
}
now = now->k[x];
}
now->ind.push_back(pz++);
}
bfs();
root->to = root;
for (auto &now : ord) {
for (int j = 0; j < 26; j++) {
if (now->k[j]) {
node* sol = now->to;
while (sol != root && !sol->k[j]) {
sol = sol->to;
}
if (now != root && sol->k[j]) {
sol = sol->k[j];
}
now->k[j]->to = sol;
}
}
}
node* state = root;
for (auto &ch : s) {
int x = ch - 'a';
while (state != root && !state->k[x]) {
state = state->to;
}
if (state->k[x]) {
state = state->k[x];
}
state->cnt++;
}
reverse(ord.begin(), ord.end());
vector<int> sol(y);
for (auto &now : ord) {
now->to->cnt += now->cnt;
for (auto &i : now->ind) {
sol[i] = now->cnt;
}
}
for (auto &x : sol) {
cout << x << "\n";
}
}
int main() {
freopen ("ahocorasick.in", "r", stdin);
//freopen ("ahocorasick.out", "w", stdout);
cin >> s;
int len;
cin >> len;
vector<string> v(len);
for (auto &x : v) {
cin >> x;
}
build(v);
}