HDU 1251 统计难题(Tire tree)

题目:

      给一个单词字典A={str[0], str[1], ...},再给定一系列的单词B = {s[0], s[1], s[2], ...}, 求字典A中以s[i]为前缀的单词有多少。

解法:

      Tire tree, 先建字典数,然后再查询每个给定的单词。

AC代码如下:

/* Author; ACb0y Date: 2010年12月4日20:21:57 ProblenID: HDU 1251 统计难题 Type: Tir tree Result: 3280541 2010-12-04 20:18:55 Accepted 1251 140MS 43760K 1198 B G++ ACb0y */ #include <stdio.h> #include <string.h> #include <malloc.h> struct node { node * child[26]; int count; }; node * root; void insert_tree(char * str) { node * pnew = NULL; node * cur = root; int length = strlen(str); for (int i = 0; i < length; ++i) { int pos = str[i] - 'a'; if (cur->child[pos] == NULL) { pnew = (node *)malloc(sizeof(node)); memset(pnew->child, 0, sizeof(node * [26])); pnew->count = 1; cur->child[pos] = pnew; cur = cur->child[pos]; } else { cur->child[pos]->count++; cur = cur->child[pos]; } } } int get_ans(char * str) { int length = strlen(str); node * cur = root; for (int i = 0; i < length; ++i) { int pos = str[i] - 'a'; if (cur->child[pos] == NULL) { cur = cur->child[pos]; break; } else { cur = cur->child[pos]; } } return cur == NULL ? 0 : cur->count; } int main() { char str[11]; #ifndef ONLINE_JUDGE freopen("in.txt", "r", stdin); #endif root = (node *)malloc(sizeof(node)); memset(root->child, 0, sizeof(node * [26])); root->count = 0; while (gets(str)) { if (strcmp(str, "") == 0) { while (gets(str)) { printf("%d/n", get_ans(str)); } } else { insert_tree(str); } } return 0; }

 

你可能感兴趣的:(HDU 1251 统计难题(Tire tree))