Pagini recente » Cod sursa (job #1394252) | Cod sursa (job #2919071) | Cod sursa (job #2141606) | Cod sursa (job #2839465) | Cod sursa (job #3198779)
#include<bits/stdc++.h>
using namespace std;
ifstream F("ahocorasick.in");
ofstream G("ahocorasick.out");
string s,a[100];
const int MAXS = 10005;
const int MAXC = 26;
int out[MAXS],b[100],n,i,m,l,t,j;
int f[MAXS];
int g[MAXS][MAXC];
int buildMatchingMachine(string arr[], int k)
{
memset(out, 0, sizeof out);
memset(g, -1, sizeof g);
int states = 1;
for (int i = 0; i < k; ++i)
{
const string &word = arr[i];
int currentState = 0, l = word.size();
for (int j = 0; j < l; ++j)
{
int ch = word[j] - 'a';
if (g[currentState][ch] == -1)
g[currentState][ch] = states++;
currentState = g[currentState][ch];
}
out[currentState] |= (1 << i);
}
for (int ch = 0; ch < MAXC; ++ch)
if (g[0][ch] == -1)
g[0][ch] = 0;
memset(f, -1, sizeof f);
queue<int> q;
for (int ch = 0; ch < MAXC; ++ch)
{
if (g[0][ch] != 0)
{
f[g[0][ch]] = 0;
q.push(g[0][ch]);
}
}
while (q.size())
{
int state = q.front();
q.pop();
for (int ch = 0; ch <= MAXC; ++ch)
{
if (g[state][ch] != -1)
{
int failure = f[state];
while (g[failure][ch] == -1)
failure = f[failure];
failure = g[failure][ch];
f[g[state][ch]] = failure;
out[g[state][ch]] |= out[failure];
q.push(g[state][ch]);
}
}
}
return states;
}
int main()
{
for(F>>s>>n;i<n;F>>a[i++]);
buildMatchingMachine(a,n);
for(i=t=0,m=s.size();i<m;++i) {
for(l=t;g[l][s[i]-97]==-1;l=f[l]);
if(t=g[l][s[i]-97],out[t])
for(j=0;j<n;++j)
if(out[t]&(1<<j))
++b[j];
}
for(i=0;i<n;G<<b[i++]<<'\n');
return 0;
}