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

Hdu1251-统计难题(字典树)

时间:2016-07-11 17:08:22      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:

Problem Description
Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).
 
Input
输入数据的第一部分是一张单词表,每行一个单词,单词的长度不超过10,它们代表的是老师交给Ignatius统计的单词,一个空行代表单词表的结束.第二部分是一连串的提问,每行一个提问,每个提问都是一个字符串.
注意:本题只有一组测试数据,处理到文件结束.
 
Output
对于每个提问,给出以该字符串为前缀的单词的数量.
 
Sample Input
banana
band
bee
absolute
acm
 
ba
b
band
abc
 
Sample Output
2
3
1
0
 
解析:在字典树插入的过程中每个位置加1。
代码
#include<cstdio>
#include<cstring>
const int maxn=500005;
struct
Tree
{

    int
next[26];
    int
info;
    void
init(){ memset(next,-1,sizeof(next)); info=0; }
}
tree[maxn];
int
id;
int
GetIndex(char c){ return c-‘a‘; }
void
Init(){ for(int i=0;i<maxn;i++) tree[i].init(); id=0; }
void
Insert(char S[])
{

    int
be=0;
    int
len=strlen(S);
    for
(int i=0;i<len;i++)
    {

        int
s=GetIndex(S[i]);
        Tree& t=tree[be];
        if
(t.next[s]==-1) t.next[s]=++id;
        be=t.next[s];
        tree[be].info++;  //加1
    }
}

int
Search(char S[])
{

    int
len=strlen(S);
    int
be=0;
    for
(int i=0;i<len;i++)
    {

        int
s=GetIndex(S[i]);
        Tree& t=tree[be];
        if
(t.next[s]==-1) return 0;  //没有找到
        be=t.next[s];
    }

    return
tree[be].info;  //返回个数
}

int
main()
{

    Init();
    char
word[11];
    while
(gets(word))
    {

        if
(word[0]==‘\0‘) break;
        Insert(word);
    }

    while
(gets(word)!=NULL)
    {

        printf("%d\n",Search(word));
    }

    return
0;
}

Hdu1251-统计难题(字典树)

标签:

原文地址:http://www.cnblogs.com/wust-ouyangli/p/5660641.html

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