hdu 1251 统计难题
https://vjudge.net/problem/HDU-1251
题意:略
思路:
经典的字典树例题,模板用上啦,见算法学习汇总。
还有就是经过这题学习到了如何判断以空行结束,那就是gets(s),s[0] == '\0' 为真就是以空行结束啦。以及hdu提交不要用g++,会mle。
代码:
1 #include <string.h> 2 #include <stdio.h> 3 4 using namespace std; 5 6 const int maxn = 26; 7 8 struct trie 9 { 10 trie *next[maxn]; 11 12 int flag; 13 14 trie() 15 { 16 flag = 1; 17 memset(next,NULL,sizeof(next)); 18 } 19 }*root; 20 21 void Insert(char *str) 22 { 23 int len = strlen(str); 24 25 trie *p = root,*q; 26 27 for (int i = 0;i < len;i++) 28 { 29 int id = str[i] - 'a'; 30 31 if (p->next[id] == NULL) 32 { 33 q = new trie(); 34 p->next[id] = q; 35 p = p -> next[id]; 36 } 37 else 38 { 39 p = p->next[id]; 40 41 ++(p->flag); 42 } 43 } 44 } 45 46 int query(char *str) 47 { 48 int len = strlen(str); 49 trie *p = root; 50 51 for (int i = 0;i < len;i++) 52 { 53 int id = str[i] - 'a'; 54 55 p = p->next[id]; 56 57 if (p == NULL) return 0; 58 } 59 60 return p->flag; 61 } 62 63 void Free(trie* T) 64 { 65 if (T == NULL) return; 66 67 for (int i = 0;i < maxn;i++) 68 { 69 if (T->next[i]) Free(T->next[i]); 70 } 71 72 delete(T); 73 } 74 75 int main() 76 { 77 char s[15]; 78 79 root = new trie(); 80 81 while (gets(s)) 82 { 83 if (s[0] == '\0') break; 84 Insert(s); 85 } 86 87 while (scanf("%s",s) != EOF) 88 { 89 int ans = query(s); 90 91 printf("%d\n",ans); 92 } 93 94 Free(root); 95 96 return 0; 97 }
康复训练中~欢迎交流!