标签:ext pre nod bsp node insert style hid span
知识点:前缀树
典型的前缀树模板。
这个版本要注意的是编译器选择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)); for (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; }
标签:ext pre nod bsp node insert style hid span
原文地址:https://www.cnblogs.com/czc1999/p/10352805.html