hdu 1251 字典树

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=27;
const int maxm=27;
char s[maxm],str[maxn];
struct node
{
    int n;
    node *next[maxn];
    node()
    {
        memset(next,0,sizeof(next));
        n=1;
    }
};
void Insert(node *rt,char *str)
{
    int i=0;
    node *p=rt;
    while(str[i])
    {
        int k=str[i++]-'a';
        if(p->next[k]==NULL) p->next[k]=new node();
       else p->next[k]->n++;
        p=p->next[k];
    }
}
int find(node *rt,char *s)
{
    int i=0,j=0;
    node *p=rt;
    while(s[i])
    {
        int k=s[i++]-'a';
        if(p->next[k]==NULL) return 0;
        p=p->next[k];
    }
    return p->n;
}
int main()
{
    //freopen("//media/学习/ACM/input.txt","r",stdin);
    node *rt=new node();
    rt->n=0;
    while(gets(s)&&strcmp(s,"")!=0)
    {
        Insert(rt,s);
    }
    while(scanf("%s",str)!=EOF)
    {
        int ans=find(rt,str);
        cout<<ans<<endl;
    }
    return 0;
}

你可能感兴趣的:(hdu 1251 字典树)