Pagini recente » Cod sursa (job #3275219) | Cod sursa (job #1767122) | Cod sursa (job #2722250) | Cod sursa (job #1584348) | Cod sursa (job #1767982)
#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;
}