Cod sursa(job #1729668)

Utilizator daniel.grosuDaniel Grosu daniel.grosu Data 15 iulie 2016 13:56:18
Problema Aho-Corasick Scor 95
Compilator cpp Status done
Runda Arhiva educationala Marime 2.44 kb
#define pb push_back
#define mp make_pair
#define first x
#define second y
#define lsb(x) x & -x
#define l(x) (x<<1)
#define r(x) ((x<<1)|1)
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef long double LD;
typedef vector<int> VI;
typedef pair<int, int> PII;
typedef pair<LL, LL> PLL;
// primes less than 100
const int PRIM[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97};
const int MOD = 1000000007;
const int NMAX = 1005666;
const double EPS = 1e-12;
const int INF16 = 32000;
const int INF = 0x3F3F3F3F;
const LL INF64 = LL(1e18);
const int dx[]={-1,1,0,0,1,-1,1,-1};
const int dy[]={0,0,1,-1,1,1,-1,-1};
// oh moy aho corasick

struct trie{
    trie* next[26];
    trie* automat[26];
    trie* fail;
    int val=0;
    VI ends;
    trie()
    {
        memset(next, 0, sizeof(next));
        memset(automat, 0, sizeof(automat));
        val=0; fail=0;
    }
};
typedef trie* ptrie;
ptrie root=new trie();

void insert(ptrie t, string c, int i, int k)
{
    if(i==c.size())
    {
        t->ends.pb(k);
        return;
    }
    if(!t->next[c[i]-'a'])
        t->next[c[i]-'a']=new trie();
    insert(t->next[c[i]-'a'], c, i+1, k);
}
int rs[NMAX];
int l=1, r=1;
ptrie q[NMAX];
void ahoc()
{
    root->fail=root;
    q[r]=root;
    for(int i=0; i<26; ++i)
        if(!root->next[i])
            root->automat[i]=root;
    while(l<=r)
    {
        ptrie v=q[l++];
        for(int i=0; i<26; ++i)
        {
            if(v->next[i])
            {
                ptrie u=v->next[i];

                v->automat[i]=u;
                if(v!=root)
                    u->fail=v->fail->automat[i];
                else
                    u->fail=root;

                q[++r]=u;

            }else
                v->automat[i]=v->fail->automat[i];
        }
    }
}

string s,c;
int n;
void read()
{
    cin>>s;
    cin>>n;

    for(int i=1; i<=n; ++i)
    {
        cin>>c;
        insert(root, c, 0, i);
    }

    ahoc();
    ptrie v=root;
    for(int i=0; i<s.size(); ++i)
    {
        v=v->automat[s[i]-'a'];
        v->val++;
    }
    for(int i=r; i>=1; --i)
    {
        ptrie v=q[i];
        v->fail->val+=v->val;
        for(auto w: v->ends)
            rs[w]=v->val;
    }
    for(int i=1; i<=n; ++i)
        cout<<rs[i]<<"\n";

}

int main()
{
    freopen("ahocorasick.in", "rt", stdin);
    freopen("ahocorasick.out", "wt", stdout);
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    read();
    return 0;
}