码迷,mamicode.com
首页 > 其他好文 > 详细

HDU 1251 统计难题

时间:2016-04-30 22:12:27      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:

  字典树应用,每个节点上对应的cnt是以它为前缀的单词的数量

#include<stdio.h>
#include<string.h>
struct trie
{
    int cnt;
    trie *next[26];
};
trie *root=new trie;
void insert(char ch[])
{
    trie *p=root,*newnode;
    for(int i=0; ch[i]!=\0; i++)
    {
        if(p->next[ch[i]-a]==0)
        {
            newnode=new trie;
            for(int j=0; j!=26; j++)
            {
                newnode->next[j]=NULL;
            }
            newnode->cnt=1;
            p->next[ch[i]-a]=newnode;
            p=newnode;
        }
        else
        {
            p=p->next[ch[i]-a];
            p->cnt++;
        }
    }
}
int find(char ch[])
{
    trie *p=root;
    for(int i=0; ch[i]!=\0; i++)
    {
        if(p->next[ch[i]-a]!=NULL)
            p=p->next[ch[i]-a];
        else
            return 0;
    }
    return p->cnt;
}
int main()
{
    char ch[20];
    for(int i=0; i!=26; i++)
    {
        root->next[i]=NULL;
    }
    root->cnt=0;
    while(gets(ch)) //±ØÐëÓÃgets
    {
        if(!strcmp(ch,"")) break;
        insert(ch);
    }
    while(scanf("%s",ch)!=EOF)
    {
        printf("%d\n",find(ch));
    }
    return 0;
}

 

HDU 1251 统计难题

标签:

原文地址:http://www.cnblogs.com/jifahu/p/5449340.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!