hdu1251 字典树

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define maxn 26//26个字母
 struct trie
{
    trie *next[maxn];//向下26个字母扩展
    int v;//记录个数
};
trie *root;
void init()
{
    root=(trie*)malloc(sizeof(trie));
    for(int i=0;i<maxn;i++)
        root->next[i]=NULL;
    root->v=0;
}
void creattrie(char *str)
{
    trie *p,*q;
    p=root;
    int i,j;
    int len=strlen(str);
    for(i=0;i<len;i++)
    {
        int id=str[i]-'a';
        if(p->next[id]==NULL)
        {
            q = (trie *)malloc(sizeof(trie));
            q->v=0;
            for(j=0;j<maxn;j++)
                q->next[j]=NULL;
            p->next[id]=q;
        }
        p=p->next[id];
        p->v++;//次数增加
    }
}
int query(char *str)
{
    int i,j;
    int len=strlen(str);
    trie *p=root;
    for(i=0;i<len;i++)
    {
        int id=str[i]-'a';
        if(p->next[id]==NULL)
            return 0;
        p=p->next[id];
    }
    return p->v;
}
int main()
{
    char str[15];
    int i,j;
    init();
    while(gets(str))
    {
        if(strcmp(str,"")==0)break;
        creattrie(str);
    }
    while(gets(str))
    {
        if(strcmp(str,"")==0)break;
        printf("%d
",query(str));
    }
}

 

原文地址:https://www.cnblogs.com/sweat123/p/4687769.html