标签:
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1251
题意:给你多个字符串,求以某个字符串为前缀的字符串数量。
思路:简单的tire数应用,在tire的数据结构中增加一个存储到当前节点字符串出现的次数,在插入的过程中维护即可。
code:
1 #include <cstdio> 2 #include <cstring> 3 const int KIND = 26; 4 struct TireNode 5 { 6 int num; // 遍历到该结点形成的字符串出现的次数 7 TireNode* next[KIND]; 8 TireNode() 9 { 10 num = 1; 11 for (int i = 0; i < KIND; ++i) next[i] = NULL; 12 } 13 }; 14 15 TireNode* root = NULL; 16 17 void Insert(char* x) 18 { 19 TireNode* temp = root; 20 if (root == NULL) // 预判 21 { 22 temp = new TireNode(); 23 root = temp; 24 } 25 int len = strlen(x); 26 for (int i = 0; i < len; ++i) 27 { 28 int curr = x[i] - ‘a‘; 29 if (temp->next[curr] != NULL) ++(temp->next[curr]->num); // 已经存在 30 else temp->next[curr] = new TireNode(); // 不存在 31 temp = temp->next[curr]; 32 } 33 } 34 35 int Search(char* x) 36 { 37 int ret = 0; 38 if (root == NULL) return ret; // 预判 39 TireNode* temp = root; 40 int len = strlen(x); 41 for (int i = 0; i < len; ++i) 42 { 43 int curr = x[i] - ‘a‘; 44 if (temp->next[curr] == NULL) return 0; 45 temp = temp->next[curr]; 46 ret = temp->num; 47 } 48 return ret; 49 } 50 51 void Release(TireNode* root) 52 { 53 if (NULL == root) return; 54 for (int i = 0; i < KIND; ++i) 55 { 56 if (root->next[i] != NULL) 57 Release(root->next[i]); 58 } 59 delete root; 60 root = NULL; 61 } 62 63 int main() 64 { 65 char str[10]; 66 while (gets(str)) 67 { 68 if (str[0] == ‘\0‘) 69 { 70 while (gets(str)) 71 printf("%d\n", Search(str)); 72 } 73 else Insert(str); 74 } 75 Release(root); 76 return 0; 77 }
标签:
原文地址:http://www.cnblogs.com/ykzou/p/4483331.html