zoukankan      html  css  js  c++  java
  • hdu 1251 统计难题(字典数)

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

    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 using namespace std;
     3 typedef struct node
     4 {
     5     node * next[26];
     6     int num;
     7     node()
     8     {
     9         num=0;
    10         memset(next,NULL,sizeof(next));
    11     }
    12 }Nod;
    13 void insert_tree(Nod * head,char *str)
    14 {
    15     Nod *h=head,*p=NULL;
    16     int len=strlen(str);
    17     int i;
    18     for(i=0;i<len;i++)
    19     {
    20         int id=str[i]-'a';
    21         if(h->next[id]==NULL)
    22             h->next[id]=new node;
    23         h->next[id]->num++;
    24         h=h->next[id];
    25     }
    26 }
    27 int find_tree(Nod *head,char *str)
    28 {
    29     int i;
    30     Nod *h=head;
    31     int len=strlen(str);
    32     for(i=0;i<len;i++)
    33     {
    34         int id=str[i]-'a';
    35         if(h->next[id]==NULL)
    36             return 0;
    37         h=h->next[id];
    38     }
    39     return h->num;
    40 }
    41 int main()
    42 {
    43     char str[11];
    44     int flag=0;
    45     Nod *head;
    46     head=new node;
    47     while(gets(str))
    48     {
    49         if(strcmp(str,"")==0)
    50         {
    51             flag=1;
    52             continue;
    53         }
    54         if(!flag)
    55             insert_tree(head,str);
    56         else
    57             printf("%d\n",find_tree(head,str));
    58     }
    59     return 0;
    60 }
  • 相关阅读:
    菜单范式
    PIC18F26K20
    单片机中串口通信模型
    STM8S103之GPIO
    STM8S103之ADC
    二叉树最近公共祖先
    全排列
    整数翻转
    完全二叉树节点个数
    二叉树的深度
  • 原文地址:https://www.cnblogs.com/crazyapple/p/2657570.html
Copyright © 2011-2022 走看看