• HDU 1251 统计难题(Trie tree)


                    统计难题



    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>
     2 #include<malloc.h>
     3 #include<cstring>
     4 using namespace std;
     5 
     6 const int maxn=26;
     7 
     8 struct Trie
     9 {
    10     Trie *next[maxn];
    11     int v;
    12     Trie()
    13     {
    14         memset(next,0,sizeof(next));
    15         v=0;
    16     }
    17 };
    18 
    19 Trie *root=new Trie;
    20 
    21 void creatTrie(char *str)
    22 {
    23     int len=strlen(str);
    24     Trie *p=root;
    25     for(int i=0;i<len;i++)
    26     {
    27         int id=str[i]-'a';
    28         if(p->next[id]==NULL)
    29         {
    30             Trie *q=new Trie;
    31             q->v=1;
    32             p->next[id]=q;
    33             p=p->next[id];
    34         }
    35         else
    36         {
    37             p->next[id]->v++;
    38             p=p->next[id];
    39         }
    40     }
    41 }
    42 
    43 int findTrie(char *str)
    44 {
    45     int i;
    46     int len=strlen(str);
    47     Trie *p=root;
    48     for(i=0;i<len;i++)
    49     {
    50         int id=str[i]-'a';
    51         if(p->next[id]==NULL)
    52             return 0;
    53         p=p->next[id];
    54     }
    55     return p->v;
    56 }
    57 
    58 int main()
    59 {
    60     //freopen("in.txt","r",stdin);
    61     char s[11];
    62     while(gets(s)&&s[0]!='')
    63     {
    64         creatTrie(s);
    65     }
    66     while(scanf("%s",s)!=EOF)
    67     {
    68         int ans=findTrie(s);
    69         printf("%d
    ",ans);
    70     }
    71     return 0;
    72 }
  • 相关阅读:
    题解 CF507A Amr and Music
    【NOIP 2020 游记--退役记】满船清梦压星河
    【CSP-2020 游记】
    【学习笔记】动态规划 DP
    【题解】洛谷 P5995 [PA2014]Lustra
    【题解】洛谷P6174 [USACO16JAN] Angry Cows S
    【题解】 洛谷 P6867 [COCI2019-2020#5] Politicari
    【题解】(LGJ原创)蝴蝶旅客
    【题解】洛谷 P6368 [COCI2006-2007#6] MAGIJA
    【题解】洛谷 P6484 [COCI2010-2011#4] ASTRO
  • 原文地址:https://www.cnblogs.com/homura/p/4696909.html
Copyright © 2020-2023  润新知