zoukankan      html  css  js  c++  java
  • 统计难题

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

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

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

    banana
    band
    bee
    absolute
    acm
    
    ba
    b
    band
    abc

    Sample Output

    2
    3
    1
    0

    字典树模板题
     1 #include <bits/stdc++.h>
     2 using namespace std;
     3 int tree[1001000][26];
     4 int num[1001000];
     5 int pos = 1;
     6 
     7 void insert(char *s){
     8     int root = 0;
     9     for(int i=0;i<strlen(s);i++){
    10         int n = s[i]-'a';
    11         if(!tree[root][n]){
    12             tree[root][n] = pos++;
    13         }
    14         root = tree[root][n];
    15         num[root]++;
    16     }
    17 }
    18 
    19 int find(char *s){
    20     int root = 0;
    21     for(int i=0;i<strlen(s);i++){
    22         int n = s[i]-'a';
    23         if(!tree[root][n]){
    24             return 0;
    25         }
    26         root = tree[root][n];
    27     }
    28     return num[root];
    29 }
    30 
    31 int main() {
    32     ios::sync_with_stdio(false);
    33     cin.tie(0);
    34     cout.tie(0);
    35     char s[15];
    36     char c;
    37     while(gets(s)){
    38         if(s[0]==NULL)
    39             break;
    40         insert(s);
    41     }
    42     while(gets(s)){
    43         cout<<find(s)<<endl;
    44     }
    45     return 0;
    46 }
  • 相关阅读:
    UIPickerView UIDatePicker的常见属性
    IOS笔记4
    判断代理是否实现了协议方法
    TableViewCell中自定义XIB的使用
    TableView中表格的添加与删除
    TableViewCell的循环使用
    NSTimer与运行循环
    IOS笔记3
    win7系统中文件夹按字母快速定位
    Intent启动常用的系统组件
  • 原文地址:https://www.cnblogs.com/zllwxm123/p/9293782.html
Copyright © 2011-2022 走看看