Pagini recente » Cod sursa (job #2211477) | Cod sursa (job #313777) | Cod sursa (job #1481988) | Cod sursa (job #1051803) | Cod sursa (job #1481810)
#include <stdio.h>
#include <cstring>
#include <vector>
#define lmax 10000010
#define hmod 1000000007
#define mod 131013
#define p 257
using namespace std;
struct trie { vector <int> y; int x; trie *t[4],*fail;
trie() {
x=0; fail=NULL;
for (int i=0;i<4;i++) t[i]=NULL;
}
};
int n,i,j,pr,ul,m,sol[50010],soll=0,curenthash;
char s[lmax],ss[27];
trie *root,*a,*q[lmax];
bool ok;
inline int min(int a,int b) { if (a<b) return a; else return b; }
vector <int> uhash[mod+5];
bool inhash(int y,int x)
{
for (unsigned int i=0;i<uhash[y].size();i++)
if (uhash[y][i]==x) return true;
return false;
}
void add_intrie()
{
trie* a=root; int i=1; n++;
while (i<=m && a->t[ss[i]-97]!=NULL) a=a->t[ss[i]-97],i++;
for (;i<=m;i++) {
a->t[ss[i]-97]=new trie; a=a->t[ss[i]-97];
}
a->y.push_back(n);
}
void bfs(trie *a)
{
trie *dolar;
a->fail=a; pr=1; ul=1; q[pr]=a;
for (;pr<=ul;pr++) {
trie *fr=q[pr];
for (int i=0;i<=3;i++)
if (fr->t[i]!=NULL) {
for (dolar=fr->fail;dolar!=a && dolar->t[i]==NULL;) dolar=dolar->fail;
if (dolar->t[i]!=NULL && dolar->t[i]!=fr->t[i]) dolar=dolar->t[i];
fr->t[i]->fail=dolar;
ul++; q[ul]=fr->t[i];
}
}
a->fail=NULL;
}
void antibfs(trie *a)
{
for (int i=ul;i>=1;i--) {
trie *fr=q[i];
if (fr->fail!=NULL) fr->fail->x+=fr->x;
for (unsigned int j=0;j<min(fr->y.size(),1);j++) sol[fr->y[j]]=fr->x;
}
}
int main() {
freopen("abc2.in","r",stdin);
freopen("abc2.out","w",stdout);
gets(s+1); n=0; root=new trie;
while (gets(ss+1)>0) {
m=strlen(ss+1); curenthash=0;
for (int i=1;i<=m;i++)
curenthash=(1LL*curenthash*p+ss[i])%hmod;
if (!inhash(curenthash%mod,curenthash))
uhash[curenthash%mod].push_back(curenthash),add_intrie();
}
bfs(root); a=root; m=strlen(s+1);
for (i=1;i<=m;i++) {
for (;a!=root && a->t[s[i]-97]==NULL;) a=a->fail;
if (a->t[s[i]-97]!=NULL) a=a->t[s[i]-97];
a->x++;
}
antibfs(root);
for (i=1;i<=n;i++) soll=soll+sol[i];
printf("%d",soll);
return 0;
}