题目:hdu 1251
题意:给定一堆单词,再给定一些前缀用于查询,每次输入一个前缀,就输出单词中以这为前缀的单词数
题解:字典树基础
代码:
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
using namespace std;
char s[15];
struct Trie//字典树
{
int cont;
Trie *c[28];
Trie()
{cont=0;for(int i=0;i<=26;i++)c[i]=NULL;}
};
Trie *root;
void insert_into(char *str)//加入字典
{
Trie *tmp=root;
int len=strlen(str);
for(int i=0;i<len;i++)
{
int pos=str[i]-'a';
if(tmp->c[pos]==NULL)
{
tmp->c[pos]=new Trie();
}
tmp=tmp->c[pos];
tmp->cont++;
}
}
int findTrie(char *str)//查找
{
Trie *tmp=root;
int len=strlen(str);
for(int i=0;i<len;i++)
{
int pos=str[i]-'a';
if(tmp->c[pos]==NULL)
{
return 0;
}
tmp=tmp->c[pos];
}
return tmp->cont;
}
void dfs(Trie *rt)//delete
{
for(int i=0;i<26;i++)
{
if(rt->c[i]!=NULL) dfs(rt->c[i]);
}
delete rt;
}
int main()
{
root=new Trie();
while(gets(s)&&strcmp(s,""))
{
insert_into(s);
}
while(~scanf("%s",s))
{
printf("%d\n",findTrie(s));
}
dfs(root);
return 0;
}

该博客主要介绍了如何使用字典树基础理论来解决HDU 1251题目,即根据给定的前缀查询与之匹配的单词数量。文章内容包括题目的描述、解决方案以及相关的代码实现。
13万+

被折叠的 条评论
为什么被折叠?



