字典樹模板題(統計難題 HDU - 1251)
阿新 • • 發佈:2018-12-06
https://vjudge.net/problem/HDU-1251
標準的字典樹模板題:
也注意一下輸入方法:
#include<iostream> #include<cstdio> #include<cstring> using namespace std; const int maxn = 26; struct node { int num; node *next[maxn]; }; //字典樹 class Tree{ public: node *head; //建構函式 Tree() { head= New(); } //建立一個新節點 node* New() { node *p = new node(); for (int i = 0; i < maxn; ++i) { p->next[i] = NULL; } p->num = 0; return p; } //插入一個字串 void insert(char *str) { int len = strlen(str); node*t, *p = head; for (int i = 0; i < len; ++i) { int c = str[i] - 'a'; if (p->next[c] == NULL) { t = New(); //建立新的節點 p->next[c] = t; } p = p->next[c]; p->num++; } }int find(char *str) { node *p = head; int len = strlen(str); for (int i = 0; i < len; ++i) { int c = str[i] - 'a'; if (p->next[c] == NULL) return 0; //不存在這樣的字串 p = p->next[c]; } return p->num; } }; int main() { char s[20]; Tree tree; while (cin.getline(s, 12)) { if (strlen(s) == 0 || strcmp(s, " ") == 0)break; //判斷是是否為空行 tree.insert(s); } while (~scanf("%s", s)) { printf("%d\n", tree.find(s)); } }