Cod sursa(job #1706041)

Utilizator daniel.grosuDaniel Grosu daniel.grosu Data 21 mai 2016 13:27:11
Problema Aho-Corasick Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.74 kb
// Template v2
#define pb push_back
#define mp make_pair
#define det(a,b,c,d)  (a*d-b*c)
#define first x
#define second y
#define l(x) (x<<1)
#define r(x) ((x<<1)|1)
#define lsb(x) x & -x
#define PI   3.14159265358979323846
#include<fstream>
#include<vector>
#include<iomanip>
#include<unordered_map>
#include<algorithm>
#include<string.h>
#include<stack>
#include<set>
#include <bitset>
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;
typedef pair<double, double> PKK;
// 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 CMAX = 100069;
const int MOD1 = 10039;
const int MOD2 = 10067;
const int MOD3 = 10429;
const int P = 73;
const int NMAX = 1005666;
const double EPS = 1e-7;
const int INF16 = 320000;
const int INF = 1e9 + 6661369;
const LL INF64 = LL(1e18);
const int dx[]={-1,1,0,0};
const int dy[]={0,0,1,-1};

ifstream cin("ahocorasick.in");
ofstream cout("ahocorasick.out");

struct trie{
    int val=0;
    vector<int>ends;
    trie *next[26];
    trie *fail;
    trie()
    {
        memset(next, 0, sizeof(next));
        fail=0;
    }
};
typedef trie* ptrie;
ptrie v, w;
ptrie root=new trie, q[NMAX];
int rs[NMAX];
int l, r, n;
string s, c;
 
void insert(int k, ptrie t=root, int i=0)
{
    if(i==c.size())
    {
        t->ends.pb(k);
        return;
    }
    
    if(t->next[c[i]-'a']==NULL)
        t->next[c[i]-'a']=new trie;
        
    insert(k, t->next[c[i]-'a'], i+1);
}

void build()
{
    l=0, r=1;
    q[++l]=root;
    root->fail=root;
    while(l<=r)
    {
        v=q[l++];
        for(int i=0; i<26; ++i)
            if(v->next[i])
            {
                w=v->next[i];
                q[++r]=w;
                w->fail=v->fail;
                while(w->fail!=root && !w->fail->next[i])
                    w->fail=w->fail->fail;
                if(w->fail->next[i] && w->fail->next[i]!=w)
                    w->fail=w->fail->next[i];
            }
    }
}

int main()
{
    cin>>s;
    cin>>n;
    
    for(int i=1; i<=n; ++i){
        cin>>c;
        insert(i);
    }
    
    build();
    ptrie v=root;
    for(int i=0; i<s.size(); ++i)
    {
        while(v!=root && v->next[s[i]-'a']==0)
            v=v->fail;
        if(v->next[s[i]-'a'])
            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";
    
    return 0;
}