问题描述:
Problem Description
Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).
Input
输入数据的第一部分是一张单词表,每行一个单词,单词的长度不超过10,它们代表的是老师交给Ignatius统计的单词,一个空行代表单词表的结束.第二部分是一连串的提问,每行一个提问,每个提问都是一个字符串.
注意:本题只有一组测试数据,处理到文件结束.
Output
对于每个提问,给出以该字符串为前缀的单词的数量.
Sample Input
banana
band
bee
absolute
acm
ba
b
band
abc
Sample Output
2
3
1
0
大致题意:
如题。
简单字典树。
ac代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <vector>
#include <queue>
using namespace std;
const int MAXN = 26;
struct Trie
{
Trie *Next[MAXN];
int Flag;
Trie()
{
Flag = 1;
memset(Next, NULL, sizeof(Next));
}
}*root;
void Insert(char *str)//插入
{
int len = strlen(str);
Trie *p = root, *q;
// 将str的每一个字符插入trie树
for(int i=0; i<len; ++i)
{
int id = str[i] - 'a';
// 如果没有边,则新建一个trie节点,产生一条边,用以代表该字符
if(p->Next[id] == NULL)
{
q = new Trie();
p->Next[id] = q;
p = p->Next[id];
}
// 如果存在边,则沿着该边走
else
{
p = p->Next[id];
// 累加以该信息为前缀的信息个数
++(p->Flag);
}
}
}
int Query(char *str)//查询操作
{
int len = strlen(str);
Trie *p = root;
// 在trie树上顺序搜索str的每一个字符
for(int i=0; i<len; ++i)
{
int id = str[i] - 'a';
p = p->Next[id];
// 若为空集,表示不存以此为前缀的信息
if(p == NULL) return 0;
}
// 返回以该信息为前缀的信息个数
return p->Flag;
}
void Free(Trie* T)//删除
{
if(T == NULL) return;
// 释放trie树的每一个节点占用的内存
for(int i=0; i<MAXN; ++i)
{
if(T->Next[i]) Free(T->Next[i]);
}
delete(T);
}
int main()
{
char ch[15];
root=new Trie();
while(gets(ch))
{
if(ch[0]=='\0')
break;
Insert(ch);
}
while(~scanf("%s",ch))
{
cout<<Query(ch)<<endl;
}
Free(root);
return 0;
}