题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5384
字典树过,把子弹存入树内,再穷举每一个怪物的子串,看看子串是否在树内存在。
1 #include <cstdio> 2 #include <cstdlib> 3 #include <cstring> 4 #include <algorithm> 5 #include <iostream> 6 #include <cmath> 7 #include <cctype> 8 #include <queue> 9 #include <map> 10 #include <set> 11 #include <stack> 12 #include <list> 13 #include <vector> 14 15 using namespace std; 16 17 const int maxn = 100010; 18 int n, m; 19 string a[maxn]; 20 char b[maxn]; 21 22 typedef struct Node { 23 Node *next[26]; 24 int cnt; 25 Node() { 26 cnt = 0; 27 for(int i = 0; i < 26; i++) { 28 next[i] = NULL; 29 } 30 } 31 }Node; 32 33 void insert(Node *p, char *str) { 34 for(int i = 0; str[i]; i++) { 35 int t = str[i] - ‘a‘; 36 if(p->next[t] == NULL) { 37 p->next[t] = new Node(); 38 } 39 p = p->next[t]; 40 } 41 p->cnt++; 42 } 43 44 int find(Node *p, string str) { 45 int res = 0; 46 for(int i = 0; str[i]; i++) { 47 int t = str[i] - ‘a‘; 48 if(p->next[t]) { 49 p = p->next[t]; 50 } 51 else { 52 break; 53 } 54 res += p->cnt; 55 } 56 return res; 57 } 58 59 void tfree(Node *root) { 60 for(int i = 0; i < 26; i++) { 61 if(root->next[i] != NULL) { 62 tfree(root->next[i]); 63 } 64 } 65 delete root; 66 } 67 68 int solve(Node* root) { 69 for(int i = 0; i < n; i++) { 70 int ans = 0; 71 for(int j = 0; j < a[i].size(); j++) { 72 ans += find(root, a[i].substr(j)); 73 } 74 printf("%d\n", ans); 75 } 76 } 77 78 int main() { 79 // freopen("in", "r", stdin); 80 int T; 81 scanf("%d", &T); 82 while(T--) { 83 Node *root = new Node(); 84 scanf("%d %d", &n, &m); 85 for(int i = 0; i < n; i++) { 86 cin >> a[i]; 87 } 88 for(int i = 0; i < m; i++) { 89 scanf("%s", b); 90 insert(root, b); 91 } 92 solve(root); 93 tfree(root); 94 } 95 return 0; 96 }
时间: 2024-10-06 22:24:15