链接:http://acm.hdu.edu.cn/showproblem.php?pid=1251
Problem Description
Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).
Input
输入数据的第一部分是一张单词表,每行一个单词,单词的长度不超过10,它们代表的是老师交给Ignatius统计的单词,一个空行代表单词表的结束.第二部分是一连串的提问,每行一个提问,每个提问都是一个字符串.
注意:本题只有一组测试数据,处理到文件结束.
注意:本题只有一组测试数据,处理到文件结束.
Output
对于每个提问,给出以该字符串为前缀的单词的数量.
Sample Input
banana band bee absolute acm ba b band abc
Sample Output
2 3 1 0
思路:字典树
字典树
基本的操作
1.建立:把母字符串每个字符串存入树,如存入ab、abc、df、de,如图
2.查找
3.插入
4.删除
搜索字典项目的方法为:
(1) 从根结点开始一次搜索;
(2) 取得要查找关键词的第一个字母,并根据该字母选择对应的子树并转到该子树继续进行检索;
(3) 在相应的子树上,取得要查找关键词的第二个字母,并进一步选择对应的子树进行检索。
(4) 迭代过程……
(5) 在某个结点处,关键词的所有字母已被取出,则读取附在该结点上的信息,即完成查找。
其他操作类似处理
节点基本结构
建立
查找
代码:
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
using namespace std;
using namespace std;
const int maxn = 200 + 10;
const int INF = (int)1e9;
struct node {
int cnt;
struct node *next[26];//指针类型?
node() {
cnt = 0;
memset(next, 0, sizeof(next));
}
};
node *root = NULL;
void buildtrie(char *s) {
node *p = root;//首先指向根节点
node *temp = NULL;//初始化
int l = strlen(s);
for (int i = 0; i < l; i++) {
if (p->next[s[i] - 'a'] == NULL) {//如果这个节点之前还没有建立
temp = new node;
p->next[s[i] - 'a'] = temp;//添加新节点
}
p = p->next[s[i] - 'a'];//跟新指针指向
p->cnt++;
}
}
void findtrie(char *s) {
node *p = root;
int l = strlen(s);
for (int i = 0; i < l; i++) {
if (p->next[s[i] - 'a'] == NULL) { //不存在的情况
printf("0\n");
return;
}
p = p->next[s[i] - 'a'];//指针不断移动
}
printf("%d\n", p->cnt);
}
void release(node *root) {
if (root == NULL) return;
for (int i = 0; i < 26; i++) {
if (root->next[i] != NULL)
release(root->next[i]);
}
free(root);
root = NULL;
}
//free()函数
//头文件:malloc.h或stdlib.h
//作用:释放malloc(或calloc、realloc)函数给指针变量分配的内存空间的函数
//用后该指针变量一定要重新指向NULL,防止野指针出现,有效 规避误操作。
int main()
{
char str[11];
root = new node;
while (gets(str)) {
if (strcmp(str, "") == 0)
break;
buildtrie(str);
}
while (scanf("%s", str) != EOF) {
findtrie(str);
}
release(root);//释放内存
//system("pause");
return 0;
}