第十二章Trie树(字典树)解决HDU1251


http://acm.hdu.edu.cn/showproblem.php?pid=1251 


#include <iostream>
using namespace std;

struct TrieNode
{
    TrieNode *children[26];
    bool flag;
    int cnt;//前缀数目
};

void InitTrieNode(TrieNode *tn)
{
    if(!tn)
    {
        exit(1);
    }
    for(int i=0;i<26;i++)
    {
        (tn->children)[i]=NULL;
    }
    tn->flag=false;
    tn->cnt=0;
}

//把长度为n的字符串a插入Trie树
void TrieTreeInsert(TrieNode **root,char *a,int n)
{
    if(!(*root))
    {
        *root=new TrieNode;
        InitTrieNode(*root);
    }
    TrieNode *tn=*root;
    
    for(int i=0;i<n;i++)
    {
        TrieNode *child=(tn->children)[a[i]-'a'];
        if(!child)
        {
            child=new TrieNode;
            InitTrieNode(child);
            (tn->children)[a[i]-'a']=child;
        }
        if(child->flag==false)
        {
            child->flag=true;
            child->cnt++;
        }
        else
        {
            child->cnt++;
        }
        tn=child;
    }
}

//统计以字符串b为前缀的单词数量
int Count(TrieNode *root,char *b,int n)
{
    int cnt=0;
    if(root)
    {
        TrieNode *tn=root;
        for(int i=0;i<n;i++)
        {
            TrieNode *child=(tn->children)[b[i]-'a'];
            if(child)
            {
                tn=child;
            }
            else
            {
                tn=NULL;
                break;
            }
        }
        if(tn!=root && tn!=NULL)
        {
            cnt=tn->cnt;
        }
    }
    return cnt;
}

int main()
{
    char a[10];
    TrieNode *root=NULL;
    while(gets(a))
    {
        int len=strlen(a);
        if(len==0)
        {
            break;
        }
        TrieTreeInsert(&root,a,len);
    }
   
    char b[10];
    while(gets(b))
    {
        int len=strlen(b);
        cout<<Count(root,b,len)<<endl;
    }
    return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值