Pagini recente » Cod sursa (job #2721761) | Cod sursa (job #1915244) | Cod sursa (job #1937361) | Cod sursa (job #3271947) | Cod sursa (job #3326921)
#include<bits/stdc++.h>
#pragma GCC optimize("Ofast,unroll-loops,inline")
#pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")
#define fast ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define setinf(x) memset(x,0x3f3f3f3f,sizeof(x));
#define set0(x) memset(x,0,sizeof(x));
#define all(x) x.begin(),x.end()
#define pii pair<int,int>
#define INF 0x3f3f3f3f
#define vi vector<int>
#define ll long long
#define vll vector<ll>
#define pb push_back
#define fi first
#define se second
#define DD 100001
#define nl '\n'
using namespace std;
const string file="ahocorasick";
ifstream f(file+".in");
ofstream g(file+".out");
//#define f cin
//#define g cout
const int SIGMA=26;
int n;
struct aho {
struct node {
int nxt[SIGMA];
int suf;
vector<int>out;
node() {
fill(nxt,nxt+SIGMA,-1);
suf=-1;
}
};
vector<node>t;
vector<int>cnt,ord;
aho() {
t.push_back(node());
}
void insert(string s, int id) {
int nod=0;
for (char c:s) {
if (t[nod].nxt[c-'a']==-1) {
t[nod].nxt[c-'a']=t.size();
t.push_back(node());
}
nod=t[nod].nxt[c-'a'];
}
t[nod].out.push_back(id);
}
void build() {
queue<int>q;
for (int i=0; i<SIGMA; ++i) {
if (t[0].nxt[i]!=-1) {
int child=t[0].nxt[i];
t[child].suf=0;
q.push(child);
}
else t[0].nxt[i]=0;
}
while (!q.empty()) {
int nod=q.front();
q.pop();
ord.push_back(nod);
int sufixtata=t[nod].suf;
for (int i=0; i<SIGMA; ++i) {
int fiu=t[nod].nxt[i];
if (fiu!=-1) {
t[fiu].suf=t[sufixtata].nxt[i];
q.push(fiu);
}
else
t[nod].nxt[i]=t[sufixtata].nxt[i];
}
}
}
vector<int>search(string txt) {
vector<int>fr(n+1,0);
cnt.assign(t.size(),0);
int nod=0;
for (char c:txt) {
nod=t[nod].nxt[c-'a'];
cnt[nod]++;
}
for (int i=(int)ord.size()-1; i>=0; i--) {
nod=ord[i];
cnt[t[nod].suf]+=cnt[nod];
}
for (int nod=0; nod<(int)t.size(); ++nod) {
for (int id:t[nod].out)
fr[id]=cnt[nod];
}
return fr;
}
};
int main(){
string t;
f>>t;
f>>n;
aho ac;
for (int i=1; i<=n; ++i) {
string s;
f>>s;
ac.insert(s,i);
}
ac.build();
vi fr=ac.search(t);
for (int i=1; i<=n; ++i) g<<fr[i]<<nl;
system("pause");
return 0;
}