HDU 2222 模板题
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <algorithm> 5 #include <queue> 6 using namespace std; 7 const int Maxn=1001000; 8 int n,Kase,sz; 9 char str[Maxn]; 10 int son[Maxn][30],Fail[Maxn],Word[Maxn]; 11 bool vis[Maxn]; 12 queue<int> Q; 13 inline void Init() 14 { 15 memset(son,0,sizeof(son)); 16 sz=1; for (int i=1;i<=26;i++) son[0][i]=1; 17 memset(Fail,0,sizeof(Fail)); 18 memset(Word,0,sizeof(Word)); 19 memset(vis,false,sizeof(vis)); 20 } 21 inline void Insert(char * S) 22 { 23 int len=strlen(S+1),pos=1; 24 for (int i=1;i<=len;i++) 25 { 26 int t=S[i]-'a'+1; 27 if (son[pos][t]) pos=son[pos][t]; else pos=son[pos][t]=++sz; 28 } 29 Word[pos]++; 30 } 31 inline void Make() 32 { 33 Q.push(1); Fail[1]=0; 34 while (!Q.empty()) 35 { 36 int u=Q.front(); Q.pop(); 37 for (int i=1;i<=26;i++) 38 if (son[u][i]) 39 { 40 int k=Fail[u]; 41 while (!son[k][i]) k=Fail[k]; 42 Fail[son[u][i]]=son[k][i]; 43 Q.push(son[u][i]); 44 } 45 } 46 } 47 inline int Solve() 48 { 49 int len=strlen(str+1),pos=1,Ans=0; 50 for (int i=1;i<=len;i++) 51 { 52 vis[pos]=true; 53 int t=str[i]-'a'+1; 54 while (!son[pos][t]) pos=Fail[pos]; 55 pos=son[pos][t]; 56 if (!vis[pos]) 57 for (int j=pos;j;j=Fail[j]) 58 { 59 Ans+=Word[j]; 60 Word[j]=0; 61 } 62 } 63 return Ans; 64 } 65 int main() 66 { 67 scanf("%d",&Kase); 68 for (int kase=1;kase<=Kase;kase++) 69 { 70 scanf("%d",&n); Init(); 71 for (int i=1;i<=n;i++) 72 { 73 scanf("%s",str+1); 74 Insert(str); 75 } 76 Make(); 77 scanf("%s",str+1); 78 printf("%d ",Solve()); 79 } 80 return 0; 81 }