#include <fstream>
#include <queue>
#include <string>
#include <unordered_map>
#include <vector>
using namespace std;
struct TrieNode
{
unordered_map<char, TrieNode*> sons;
TrieNode *suffix = nullptr;
vector<int> indexes;
int count = 0;
bool HasSon(char ch) const;
TrieNode* Son(char ch);
};
bool TrieNode::HasSon(char ch) const
{
return sons.count(ch) > 0;
}
TrieNode* TrieNode::Son(char ch)
{
auto it = sons.find(ch);
if (it != sons.end()) {
return it->second;
}
sons.insert({ch, new TrieNode});
return sons[ch];
}
void Insert(TrieNode *root, int index, const string &str, size_t pos = 0)
{
if (pos >= str.size()) {
root->indexes.push_back(index);
return;
}
Insert(root->Son(str[pos]), index, str, pos + 1);
}
TrieNode* FindSuffixNode(TrieNode *father, char ch)
{
if (!father->suffix) {
return father;
}
auto other = father->suffix;
while (other->suffix && !other->HasSon(ch)) {
other = other->suffix;
}
if (other->HasSon(ch)) {
other = other->Son(ch);
}
return other;
}
vector<TrieNode*> MakeAutomaton(TrieNode *root)
{
vector<TrieNode*> order;
order.push_back(root);
size_t index = 0;
while (index < order.size()) {
auto node = order[index++];
for (const auto &p : node->sons) {
p.second->suffix = FindSuffixNode(node, p.first);
order.push_back(p.second);
}
}
return order;
}
void ExtractCount(const vector<TrieNode*> &order, vector<int> &count)
{
for (int i = order.size() - 1; i >= 0; i -= 1) {
auto node = order[i];
for (const auto &index : node->indexes) {
count[index] = node->count;
}
if (node->suffix) {
node->suffix->count += node->count;
}
}
}
vector<int> CountAppearances(int words,
const vector<TrieNode*> &order,
const string &text)
{
auto *node = order[0];
for (const auto &ch : text) {
while (!node->HasSon(ch) && node->suffix) {
node = node->suffix;
}
if (node->HasSon(ch)) {
node = node->Son(ch);
}
node->count += 1;
}
vector<int> count(words, 0);
ExtractCount(order, count);
return count;
}
int main()
{
ifstream fin("ahocorasick.in");
ofstream fout("ahocorasick.out");
string text;
getline(fin, text);
int words;
fin >> words;
fin.get();
TrieNode *trie = new TrieNode;
for (auto i = 0; i < words; i += 1) {
string word;
getline(fin, word);
Insert(trie, i, word);
}
auto order = MakeAutomaton(trie);
auto res = CountAppearances(words, order, text);
for (const auto &count : res) {
fout << count << "\n";
}
return 0;
}