Cod sursa(job #1767982)

Utilizator sulzandreiandrei sulzandrei Data 29 septembrie 2016 23:02:11
Problema Aho-Corasick Scor 55
Compilator cpp Status done
Runda Arhiva educationala Marime 1.37 kb
#include <iostream>

#include <fstream>
#include <string>
#include <map>
#include <vector>
#include <string>
#include <unordered_map>
#include <algorithm>
using namespace std;

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

void kmp_table(string& w,vector<int>& t)
{
    t.resize(w.size()+1);
    int pos = 2,cnd = 0;
    t[0] = -1,t[1] = 0;
    while(pos <= w.size())
    {
        if(w[pos-1] == w[cnd])
        {
            t[pos] = cnd+1;
            cnd++;
            pos++;
        }
        else if(cnd>0)
            cnd = t[cnd];
        else
        {
            t[pos] = 0;
            pos++;
        }
    }
}
void kmp(string &s, string&w, vector<int> &pos)
{
    int m = 0 , i = 0;
    vector<int> t;
    //cout<<w<<"\n"<<s;
    kmp_table(w,t);
    while( m + i <s.size() )
    {
        if(w[i] == s[m+i])
        {
            if(i == w.size()-1)
                pos.push_back(m);
            i++;
        }
        else
            if(t[i] > -1)
                m = m + i - t[i],i = t[i];
            else
                m++ , i = 0;
    }
}
int main()
{
    string a,word;
    vector<int> pos;
    int n;
    in >> a;
    in >> n;
    for(int i = 0 ; i < n ; i++)
    {
        in >> word;
        kmp(a,word,pos);
        out<<pos.size()<<'\n';
        pos.clear();
    }


    return 0;
}