HDU1251:http://acm.hdu.edu.cn/showproblem.php?pid=1251
初学字典树,码模板……
#include<iostream> #include<string.h> using namespace std; char a[15]; struct node { node *nextt[26]; int v=0; }; node root; void init() { for (int i = 0; i < 26; i++) { root.nextt[i] = NULL; } } void creatree() { int len = strlen(a); node *p = &root,*q; for (int i = 0; i < len; i++) { int id = a[i] - ‘a‘; if (p->nextt[id] == NULL) { q = (node*)malloc(sizeof(node)); q->v = 1; for (int j = 0; j < 26; j++) q->nextt[j] = NULL; p->nextt[id] = q; p = p->nextt[id]; } else { p->nextt[id]->v++; p = p->nextt[id]; } } } int find() { int len = strlen(a); node *p = &root; for (int i = 0; i < len; i++) { int id = a[i] - ‘a‘; p = p->nextt[id]; if (p == NULL) return 0; } return p->v; } int main() { init(); while (gets(a) && a[0] != ‘\0‘) creatree(); while (cin >> a) { cout << find() << endl; } return 0; }
时间: 2024-10-28 10:17:58