Pagini recente » Cod sursa (job #1786368) | Cod sursa (job #989127) | Cod sursa (job #2341919)
#include <fstream>
#include <map>
#include <queue>
#include <string>
#include <vector>
using namespace std;
struct TrieNode
{
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;
}
void MakeAutomaton(TrieNode *root)
{
queue<TrieNode*> q;
q.push(root);
while (!q.empty()) {
auto node = q.front();
q.pop();
for (const auto &p : node->sons) {
p.second->suffix = FindSuffixNode(node, p.first);
q.push(p.second);
}
}
}
void ExtractCount(TrieNode *trie, vector<int> &count)
{
vector<TrieNode*> order;
size_t index = 0;
order.push_back(trie);
while (index < order.size()) {
auto node = order[index++];
for (const auto &p : node->sons) {
order.push_back(p.second);
}
}
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, TrieNode *trie, const string &text)
{
TrieNode *node = trie;
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(trie, 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);
}
MakeAutomaton(trie);
auto res = CountAppearances(words, trie, text);
for (const auto &count : res) {
fout << count << "\n";
}
return 0;
}