隨手練——HDU 1251 統計難題
阿新 • • 發佈:2019-02-05
bre hdu str 編譯器 實現 include pass mes sin
知識點:前綴樹
典型的前綴樹模板。
這個版本要註意的是編譯器選擇C++可以AC,用G++就超內存了。
#include <iostream> #include <malloc.h> #include <string> using namespace std; typedef struct node{ int pass; struct node* next[26]; } *trieTree; trieTree init() { trieTree t = (trieTree)malloc(sizeof(node));View Codefor (int i = 0; i < 26; i++)t->next[i] = NULL; t->pass = 0; return t; } void insert(trieTree T,string s) { node *n = T; for (int i = 0; i < s.length(); i++) { int index = s[i] - ‘a‘; if (T->next[index] == NULL) { node *t = init(); T->next[index] = t; } T = T->next[index]; T->pass++; } } int find(trieTree T, string s) { node *n = T; for (int i = 0; i < s.length(); i++) { int index = s[i] - ‘a‘; if (T->next[index] == NULL) { return NULL; } T= T->next[index]; } return T->pass; } int main() { trieTree T = init(); string s; while (getline(cin,s)) { if (s.empty()) break; insert(T, s); } while (getline(cin,s)) { cout << find(T, s) << endl; } return 0; }
過不了,我還想了半天,網上別人代碼都能AC,我咋過不了???人醜就不給過???這個難受啊。
其實,next指針數組,浪費了很多空間,用STL map重新改了一下(malloc只分配內存,我改成了new),內存大約節省了25%~30(自己實現一個簡單鍵值對,節省的空間會更多),C++、G++編譯器都能AC了。
#include <iostream> #include <map> #include <string> using namespace std; typedef struct node{ int pass; map<char,struct node *>m; } *trieTree; trieTree init() { trieTree t = new node; t->pass = 0; return t; } void insert(trieTree T,string s) { for (int i = 0; i < s.length(); i++) { if (T->m.find(s[i]) == T->m.end()) { node *t = init(); T->m.insert(make_pair(s[i], t)); } T = T->m[s[i]]; T->pass++; } } int find(trieTree T, string s) { node *n = T; for (int i = 0; i < s.length(); i++) { if (T->m.find(s[i]) == T->m.end()) { return NULL; } T = T->m[s[i]]; } return T->pass; } int main() { trieTree T = init(); string s; while (getline(cin,s)) { if (s.empty()) break; insert(T, s); } while (getline(cin,s)) { cout << find(T, s) << endl; } return 0; }
隨手練——HDU 1251 統計難題