标签:des style blog http java color os strong
Time Limit: 2000/1000 MS (Java/Others)
Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 33431 Accepted Submission(s): 10800
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <cmath> 5 #include <algorithm> 6 #include <climits> 7 #include <vector> 8 #include <queue> 9 #include <cstdlib> 10 #include <string> 11 #include <set> 12 #define LL long long 13 #define INF 0x3f3f3f3f 14 using namespace std; 15 const int maxn = 250010; 16 struct trie { 17 int letter[26],fail; 18 int cnt; 19 } dic[maxn]; 20 int tot = 1; 21 char str[1000100]; 22 void insertWord(int root,char *s) { 23 for(int i = 0; s[i]; i++) { 24 int k = s[i]-‘a‘; 25 if(dic[root].letter[k] == -1) 26 dic[root].letter[k] = tot++; 27 root = dic[root].letter[k]; 28 } 29 dic[root].cnt++; 30 } 31 queue<int>q; 32 void build(int root) { 33 dic[root].fail = root; 34 q.push(root); 35 while(!q.empty()) { 36 int u = q.front(),v; 37 q.pop(); 38 for(int i = 0; i < 26; i++) { 39 if(dic[u].letter[i] == -1) continue; 40 if(u == 0) dic[dic[u].letter[i]].fail = 0; 41 else { 42 v = dic[u].fail; 43 while(v && dic[v].letter[i] == -1) v = dic[v].fail; 44 if(dic[v].letter[i] == -1) dic[dic[u].letter[i]].fail = 0; 45 else dic[dic[u].letter[i]].fail = dic[v].letter[i]; 46 } 47 q.push(dic[u].letter[i]); 48 } 49 } 50 } 51 int query(int root,char *s) { 52 int i,ans = 0; 53 for(i = 0; s[i]; i++) { 54 int k = s[i]-‘a‘; 55 while(root && dic[root].letter[k] == -1) 56 root = dic[root].fail; 57 if(dic[root].letter[k] != -1) { 58 int v = dic[root].letter[k]; 59 while(dic[v].cnt) { 60 if(dic[v].cnt) { 61 ans += dic[v].cnt; 62 dic[v].cnt = 0; 63 } 64 v = dic[v].fail; 65 } 66 ans += dic[v].cnt; 67 dic[v].cnt = 0; 68 root = dic[root].letter[k]; 69 } 70 } 71 return ans; 72 } 73 int main() { 74 int i,j,m,t; 75 char temp[100]; 76 scanf("%d",&t); 77 while(t--) { 78 tot = 1; 79 scanf("%d",&m); 80 while(!q.empty()) q.pop(); 81 for(i = 0; i < maxn; i++) { 82 dic[i].cnt = 0; 83 dic[i].fail = 0; 84 memset(dic[i].letter,-1,sizeof(dic[i].letter)); 85 } 86 while(m--) { 87 scanf("%s",temp); 88 insertWord(0,temp); 89 } 90 build(0); 91 scanf("%s",str); 92 printf("%d\n",query(0,str)); 93 } 94 return 0; 95 }
hdu 2222 Keywords Search,布布扣,bubuko.com
标签:des style blog http java color os strong
原文地址:http://www.cnblogs.com/crackpotisback/p/3873017.html