• hdoj1251-统计难题 【字典树】


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

    统计难题

    Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 131070/65535 K (Java/Others)
    Total Submission(s): 19902    Accepted Submission(s): 8720


    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 <iostream>
     2 #include <cstdio>
     3 #include <cstdlib>
     4 #include <cstring>
     5 #include <algorithm>
     6 #include <string>
     7 #include <map>
     8 using namespace std;
     9 
    10 #define MAX 0x7fffffff
    11 
    12 struct node{
    13     node* word[26];
    14     int n;
    15     node(){
    16         for(int i=0;i<26;i++)   word[i]=NULL;
    17         n=1;
    18     }
    19 }*root;
    20 
    21 void Insert(char* s);
    22 int Find(char* s);
    23 
    24 int main(){
    25     //freopen("D:\input.in","r",stdin);
    26     //freopen("D:\output.out","w",stdout);
    27     char tmp[20];
    28     root=new node;
    29     while(gets(tmp),strlen(tmp)){
    30         Insert(tmp);
    31     }
    32     while(gets(tmp)!=NULL){
    33         printf("%d
    ",Find(tmp));
    34     }
    35     return 0;
    36 }
    37 void Insert(char* s){
    38     int len=strlen(s);
    39     node *current=root,*new_node;
    40     for(int i=0;i<len;i++){
    41         if(current->word[s[i]-'a']!=NULL){
    42             current=current->word[s[i]-'a'];
    43             current->n++;
    44         }else{
    45             new_node=new node;
    46             current->word[s[i]-'a']=new_node;
    47             current=current->word[s[i]-'a'];
    48         }
    49     }
    50 }
    51 int Find(char* s){
    52     int len=strlen(s);
    53     node *current=root;
    54     for(int i=0;i<len;i++){
    55         if(current->word[s[i]-'a']!=NULL){
    56             current=current->word[s[i]-'a'];
    57         }else{ return 0; }
    58     }
    59     return current->n;
    60 }
  • 相关阅读:
    codeforces707B:Bakery
    codeforces707A:Brain's Photos
    BZOJ1084 [SCOI2005]最大子矩阵
    BZOJ1264 [AHOI2006]基因匹配Match
    BZOJ2764 [JLOI2011]基因补全
    codevs1257 打砖块
    BZOJ1079 [SCOI2008]着色方案
    BZOJ1026 [SCOI2009]windy数
    菜鸟学自动化测试(一)----selenium IDE
    关于w3school的html5部分output 元素实例代码(点亲自试一试进去)的问题纠正
  • 原文地址:https://www.cnblogs.com/jiu0821/p/4302033.html
Copyright © 2020-2023  润新知