统计难题
来源:互联网 发布:linux守护进程 编辑:程序博客网 时间:2024/05/22 06:40
http://acm.hdu.edu.cn/showproblem.php?pid=1251
#include<iostream>
#include<cstring>
using namespace std;
struct trie
{
int count;
trie *next[26];
};
trie *root;
trie *create()
{
trie *t=(trie*)malloc(sizeof(trie));
memset(t,0,sizeof(trie));
return t;
}
void Insert(char *ch)
{
trie *s=root;
for(int i=0;ch[i];i++)
{
if(s->next[ch[i]-'a'])
{
s=s->next[ch[i]-'a'];
s->count=s->count+1;
}
else
{
s->next[ch[i]-'a']=create();
s=s->next[ch[i]-'a'];
s->count=1;
}
}
}
int Search(char *ch)
{
int i;
trie *s=root;
for(i=0;ch[i];i++)
{
if(s->next[ch[i]-'a'])
s=s->next[ch[i]-'a'];
else
return 0;
}
if(ch[i]==0)
return s->count;
}
int main()
{
// freopen("C:\\Users\\John\\Desktop\\hi.txt","r",stdin);
char sh[20];
root=create();
while(gets(sh) && strlen(sh))
{
Insert(sh);
}
while(gets(sh)!=NULL)
{
cout<<Search(sh)<<endl;
}
return 0;
}