题目链接:HDUOJ 1251
算法分析:字典树裸题。
下面是AC代码:
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int maxn=26;
struct node
{
int Count;
node * next[maxn];
node()
{
Count=0;
memset(next,0,sizeof(next));
}
};
node *p,*root=new node();
void Insert(char s[])//建树
{
p=root;
for(int i=0;s[i];i++)//将字符串中的字符依次插入到字典树中
{
int id=s[i]-'a';
if(p->next[id]==NULL) p->next[id]=new node();//如果该节点不存在就新建
p=p->next[id];//往子节点走
p->Count++;//以此为前缀的单词数加1
}
}
int Query(char s[])//查询
{
p=root;
int i;
for(i=0;s[i];i++)
{
int id=s[i]-'a';
if(p->next[id]==NULL) return 0;//不存在这样的节点
p=p->next[id];//存在继续往下走
}
return p->Count;
}
int main()
{
char s[maxn];
while(gets(s),*s) Insert(s);
while(gets(s)) cout<<Query(s)<<endl;
return 0;
}