題目: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;
}