Pagini recente » Rating Vornicu Catalin-Paul (ashiulop) | Cod sursa (job #663624) | Cod sursa (job #1085843) | Cod sursa (job #1648029) | Cod sursa (job #2341891)
#include <fstream>
#include <map>
#include <queue>
#include <string>
#include <vector>
using namespace std;
struct TrieNode
{
map<char, TrieNode*> sons;
TrieNode *father = nullptr;
TrieNode *suffix = nullptr;
TrieNode *output = nullptr;
vector<int> indexes;
TrieNode(TrieNode *father = nullptr) : father(father) {}
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(this)});
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 *node, char ch)
{
if (!node->father->suffix) {
return node->father;
}
auto other = node->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<pair<char, TrieNode*>> q;
q.push({'\0', root});
while (!q.empty()) {
auto ch = q.front().first;
auto node = q.front().second;
q.pop();
if (ch != '\0') {
node->suffix = FindSuffixNode(node, ch);
if (!node->suffix->indexes.empty()) {
node->output = node->suffix;
} else {
node->output = node->suffix->output;
}
}
for (const auto &p : node->sons) {
q.push({p.first, p.second});
}
}
}
vector<int> CountAppearances(int words, TrieNode *trie, const string &text)
{
vector<int> count(words, 0);
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);
}
auto output = node;
while (output) {
for (const auto &index : output->indexes) {
count[index] += 1;
}
output = output->output;
}
}
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;
}