Cod sursa(job #1729681)

Utilizator daniel.grosuDaniel Grosu daniel.grosu Data 15 iulie 2016 14:20:20
Problema Aho-Corasick Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.34 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* fail;
    int val;
    VI ends;
    trie()
    {
        memset(next, 0, sizeof(next));
        val=0;
        fail=0;
    }
};
typedef trie* ptrie;
ptrie root=new trie();

string c;
void insert(ptrie t, 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'], i+1, k);
}
int rs[200];
int l=1, r=1;
ptrie q[300000];
void ahoc()
{
    root->fail=root;
    q[r]=root;

    while(l<=r)
    {
        ptrie v=q[l++];
        for(int i=0; i<26; ++i)
        {

            if(v->next[i])
            {
                ptrie u=v->next[i];

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

                q[++r]=u;


            }else
                if(v==root)
                    v->next[i]=root;
                else
                    v->next[i]=v->fail->next[i];
        }
    }
}

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

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

    ahoc();
    ptrie v=root;

    for(int i=0; i<s.size(); ++i)
    {
        v=v->next[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;
}