hdu 2222
统计 模板串出现的总数。
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <queue> 5 6 #define MAXN 1100010 7 #define SIG 26 8 using namespace std; 9 10 struct AC{ 11 int ch[MAXN][SIG]; 12 int f[MAXN]; 13 int val[MAXN]; 14 int cnt; 15 bool flag[MAXN]; 16 int las[MAXN]; 17 int ans; 18 void init(){ 19 memset(ch[0],0,sizeof(ch[0])); 20 memset(flag,0,sizeof(flag)); 21 val[0] = las[0] = 0; 22 cnt = 1; 23 24 ans = 0; 25 } 26 int idx(char x){return x-'a';} 27 void insert(char *P,int v){ 28 int m = strlen(P); 29 int r = 0; 30 for(int i=0;i<m;i++){ 31 int c = idx(P[i]); 32 if(!ch[r][c]){ 33 ch[r][c] = cnt; 34 memset(ch[cnt],0,sizeof(ch[cnt])); 35 val[cnt] = 0; 36 las[cnt] = 0; 37 cnt ++; 38 } 39 r = ch[r][c]; 40 } 41 val[r] += 1; 42 /// 43 } 44 void find(char *T){ 45 int n=strlen(T); 46 int j = 0; 47 for(int i = 0; i < n; i ++){ 48 int c = idx(T[i]); 49 while(j && !ch[j][c]) j = f[j]; 50 j = ch[j][c]; 51 ////// 52 if(val[j]) print(j); 53 else print(las[j]); 54 } 55 } 56 void print(int j){ 57 if(!j) return ; 58 if(!flag[j]) ans += val[j]; 59 flag[j] = true; 60 print(las[j]); 61 } 62 void getfail(){ 63 queue<int> q; 64 f[0] = 0; 65 for(int c = 0 ; c < SIG; c++){ 66 int u = ch[0][c]; 67 if(u){ f[u] = 0; q.push(u); las[u] = 0;} 68 } 69 while(!q.empty()){ 70 int r = q.front(); q.pop(); 71 for(int c = 0; c < SIG; c++){ 72 int u=ch[r][c]; 73 if(!u)continue; 74 q.push(u); 75 int v = f[r]; 76 while(v && !ch[v][c]) v = f[v]; 77 f[u] = ch[v][c]; 78 ///// 79 las[u] = val[f[u]] ? f[u] : las[f[u]]; 80 } 81 } 82 } 83 }ac; 84 char str[MAXN]; 85 int main() 86 { 87 int _,n; 88 cin>>_; 89 while(_--){ 90 scanf("%d",&n); 91 ac.init(); 92 for(int i = 0;i < n;i ++){ 93 scanf("%s",str); 94 ac.insert(str,1); 95 } 96 ac.getfail(); 97 scanf("%s",str); 98 ac.find(str); 99 printf("%d\n",ac.ans); 100 } 101 return 0; 102 } 103 /* 104 4 105 4 106 a 107 aa 108 aaa 109 aaaa 110 aaaa 111 */

浙公网安备 33010602011771号