zoukankan      html  css  js  c++  java
  • HDU1251 统计难题(字典树|map

    Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).

    Input输入数据的第一部分是一张单词表,每行一个单词,单词的长度不超过10,它们代表的是老师交给Ignatius统计的单词,一个空行代表单词表的结束.第二部分是一连串的提问,每行一个提问,每个提问都是一个字符串.

    注意:本题只有一组测试数据,处理到文件结束.
    Output对于每个提问,给出以该字符串为前缀的单词的数量.
    Sample Input

    banana
    band
    bee
    absolute
    acm
    
    ba
    b
    band
    abc

    Sample Output

    2
    3
    1
    0

    先贴map做法
     1 #include<bits/stdc++.h>
     2 using namespace std;
     3 map<string,int>mp;
     4 string s;
     5 int main()
     6 {
     7     while(getline(cin,s)&&s!=""){
     8         int l =s.size();
     9         string str;
    10         for(int i = 0;i < l;++i){
    11             str += s[i];
    12             mp[str]++;
    13         }
    14     } 
    15     while(cin>>s){
    16         cout<<mp[s]<<endl;
    17     }
    18     return 0;
    19 }
     1 #include<iostream>
     2 #include<stdio.h>
     3 #include<string.h>
     4 char s[106];int ans= 0;
     5 struct node{
     6     int count;
     7     node *next[27];
     8     node(){for(int i=0;i<27;i++) next[i]=nullptr;count=0;}
     9 };
    10 node *p,root;
    11 void build_tree(){
    12     int l = strlen(s);
    13     node *p=&root;
    14     for(int i = 0;i < l;++i){
    15         if(p->next[s[i]-'a']==NULL){
    16             p->next[s[i]-'a'] = new node;
    17         }
    18         p=p->next[s[i]-'a'];
    19         p->count++;
    20     }
    21 }
    22 
    23 int search(){
    24     int l = strlen(s);
    25     node *p=&root;
    26     for(int i=0;i <l;++i){
    27         if(!p->next[s[i]-'a']) return 0;
    28         p=p->next[s[i]-'a'];
    29     }
    30     return p->count;
    31 }
    32 int main()
    33 {
    34     while(gets(s)){
    35         if(strlen(s)==0) break;
    36         build_tree();
    37     }
    38     while(gets(s)){
    39         printf("%d
    ",search());
    40     }
    41     return 0;
    42 }
  • 相关阅读:
    ruby 中的respond_to (转)
    outlook最小化到托盘的设置方法
    FCKeditor 在VS2008下的用法
    暴风影音2009开机启动关闭方法
    构建自己的不可替代性
    MySQL安装1045错解决办法(绝对经典)
    如何学好C++,用好类库很重要
    转:什么是重构
    转:C++堆与栈的区别
    SQL Server 中的索引
  • 原文地址:https://www.cnblogs.com/h404nofound/p/11700564.html
Copyright © 2011-2022 走看看