HDU 1251 统计难题(字典树)

第一道Trie树留念。

Trie树参考资料:http://www.wutianqi.com/?p=1359

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef struct Trie
{
    int v;
    Trie *next[26];
}Trie;
Trie root;
void CreateTrie(char *str)
{
    int len=strlen(str);
    Trie *p=&root,*q;
    for(int i=0;i<len;i++)
    {
        int id=str[i]-'a';
        if(p->next[id]==NULL)
        {
            q=(Trie *)malloc(sizeof(root));
            for(int j=0;j<26;j++)
                q->next[j]=NULL;
            p->next[id]=q;
            p->next[id]->v=1;
            p=p->next[id];
        }
        else
        {
            p->next[id]->v++;
            p=p->next[id];
        }
    }
}
int findTrie(char *str)
{
    int len=strlen(str);
    Trie *p=&root;
    for(int i=0;i<len;i++)
    {
        int id=str[i]-'a';
        p=p->next[id];
        if(p==NULL)
            return 0;
    }
    return p->v;
}
int main()
{
    char word[15];
    for(int i=0;i<26;i++)
        root.next[i]=NULL;
    while(gets(word)&&word[0]!='\0')
        CreateTrie(word);
    memset(word,0,sizeof(word));
    while(~scanf("%s",word)){
        int ans=findTrie(word);
        printf("%d\n",ans);
    }
    return 0;
}


你可能感兴趣的:(HDU 1251 统计难题(字典树))