标签:using des turn for limit this users others cas
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 66208 Accepted Submission(s):
22193
1 #include<cstdio> 2 #include<algorithm> 3 #include<cstring> 4 #include<queue> 5 6 using namespace std; 7 8 const int MAXN = 500100; 9 10 char str[1000100],s[110]; 11 12 struct Aczdj{ 13 int ch[MAXN][26],val[MAXN],last[MAXN],fail[MAXN],size,ret; 14 void clear() 15 { 16 memset(ch[0],0,sizeof(ch[0])); 17 memset(val,0,sizeof(val)); 18 memset(fail,0,sizeof(fail)); 19 size = 0; 20 ret = 0; 21 } 22 int idx(char c) 23 { 24 return c-‘a‘; 25 } 26 void insert(char *s) 27 { 28 int u = 0,len = strlen(s); 29 for (int i=0; i<len; ++i) 30 { 31 int c = idx(s[i]); 32 if (!ch[u][c]) 33 { 34 ch[u][c] = ++size; 35 val[size] = 0; 36 memset(ch[size],0,sizeof(ch[size])); 37 } 38 u = ch[u][c]; 39 } 40 val[u] ++; 41 } 42 void getfail() 43 { 44 queue<int>q; 45 fail[0] = 0; 46 for (int c=0; c<26; ++c) 47 { 48 int u = ch[0][c]; 49 if (u) 50 { 51 fail[u] = 0;q.push(u);last[u] = 0; 52 } 53 } 54 while (!q.empty()) 55 { 56 int r = q.front();q.pop(); 57 for (int c=0; c<26; ++c) 58 { 59 int u = ch[r][c]; 60 if (!u) 61 { 62 ch[r][c] = ch[fail[r]][c];//有这一行就可以减去89行 63 continue; 64 } 65 q.push(u); 66 int v = fail[r]; 67 while (v && !ch[v][c]) v = fail[v]; 68 fail[u] = ch[v][c]; 69 last[u] = val[fail[u]] ? fail[u] : last[fail[u]]; 70 } 71 } 72 } 73 void solve(int j) 74 { 75 if (!j) return ; 76 if (val[j]) 77 { 78 ret += val[j]; 79 val[j] = 0; 80 } 81 solve(last[j]); 82 } 83 void find(char *T) 84 { 85 int j = 0,len = strlen(T); 86 for (int i=0; i<len; ++i) 87 { 88 int c = idx(T[i]); 89 // while (j && !ch[j][c]) j = fail[j]; 90 j = ch[j][c]; 91 if (val[j]) solve(j); 92 else if (last[j]) solve(last[j]); 93 } 94 } 95 96 }ac; 97 98 int main() 99 { 100 int t,n; 101 scanf("%d",&t); 102 while (t--) 103 { 104 ac.clear(); 105 scanf("%d",&n); 106 while (n--) 107 { 108 scanf("%s",s); 109 ac.insert(s); 110 } 111 ac.getfail(); 112 scanf("%s",str); 113 ac.find(str); 114 printf("%d\n",ac.ret); 115 } 116 return 0; 117 }
hdu:2222:Keywords Search(AC自动机模板题)
标签:using des turn for limit this users others cas
原文地址:http://www.cnblogs.com/mjtcn/p/7371870.html