Pagini recente » Cod sursa (job #1730886) | Cod sursa (job #1906353) | Cod sursa (job #866993) | Cod sursa (job #781313) | Cod sursa (job #2447944)
#include <bits/stdc++.h>
using namespace std;
const int L_MAX = 1000002;
const int N_MAX = 102;
const int W_MAX = 10002;
ifstream fin ("ahocorasick.in");
ofstream fout ("ahocorasick.out");
struct Trie
{
int index;
int ap;
Trie* sons[26];
Trie* maxPref;
Trie* maxW;
int apSubstr;
Trie ()
{
index = 0;
for(int i = 0; i < 26; i++)
sons[i] = NULL;
ap = 0;
maxPref = NULL;
maxW = NULL;
apSubstr = 0;
}
};
Trie* Root = new Trie();
void trieInsert (Trie* root, char* str, int index)
{
if(str[0] == '\0')
{
root->ap++;
if(root->index == 0)
root->index = index;
}
else
{
if(root->sons[str[0] - 'a'] == NULL)
root->sons[str[0] - 'a'] = new Trie();
trieInsert(root->sons[str[0] - 'a'], str + 1, index);
}
}
char a[L_MAX];
int n;
pair <string, int> w[N_MAX];
queue <Trie*> q;
vector <Trie*> order;
void bfs ()
{
Root->maxPref = Root->maxW = Root;
q.push(Root);
while(!q.empty())
{
Trie* root = q.front();
order.push_back(root);
q.pop();
for(int i = 0; i < 26; i++)
if(root->sons[i] != NULL)
{
root->sons[i]->maxPref = root->maxPref;
while(root->sons[i]->maxPref != Root && root->sons[i]->maxPref->sons[i] == NULL)
root->sons[i]->maxPref = root->sons[i]->maxPref->maxPref;
if(root->sons[i]->maxPref->sons[i] != NULL && root != Root)
root->sons[i]->maxPref = root->sons[i]->maxPref->sons[i];
root->sons[i]->maxW = root->sons[i]->maxPref;
if(root->sons[i]->maxW->ap == 0)
root->sons[i]->maxW = root->sons[i]->maxW->maxW;
q.push(root->sons[i]);
}
}
}
int answer[N_MAX];
int answer1[N_MAX];
void getFreq ()
{
Trie* p = Root;
int lga = strlen(a);
for(int i = 0; i < lga; i++)
{
while(p != Root && p->sons[a[i] - 'a'] == NULL)
p = p->maxPref;
if(p->sons[a[i] - 'a'] != NULL)
p = p->sons[a[i] - 'a'];
p->apSubstr++;
}
}
void getAnswer (string s = "")
{
reverse(order.begin(), order.end());
for(Trie* node : order)
{
node->maxPref->apSubstr += node->apSubstr;
answer[node->index] = node->apSubstr;
}
}
char str[W_MAX];
int main()
{
fin >> a;
fin >> n;
for(int i = 1; i <= n; i++)
{
fin >> w[i].first;
w[i].second = i;
}
sort(w + 1, w + n + 1);
for(int i = 1; i <= n; i++)
{
strcpy(str, w[i].first.c_str());
trieInsert(Root, str, i);
}
bfs();
getFreq();
memset(answer, -1, sizeof(answer));
getAnswer();
for(int i = 1; i <= n; i++)
{
if(answer[i] == -1)
answer[i] = answer[i - 1];
answer1[w[i].second] = answer[i];
}
for(int i = 1; i <= n; i++)
fout << answer1[i] << "\n";
return 0;
}