• hdu1251 统计难题


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


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

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

    注意:本题只有一组测试数据,处理到文件结束.
     

    Output
    对于每个提问,给出以该字符串为前缀的单词的数量.
     

    Sample Input
    banana band bee absolute acm ba b band abc
     

    Sample Output
    2 3 1 0
     
    这是一道trie树的简单题。建立一棵trie树的时间是n*k(n是字符串的个数,k是字符串的长度),插入和查询单个字符串的时间都是k。

    #include<iostream>
    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    #include<math.h>
    #include<vector>
    #include<map>
    #include<set>
    #include<queue>
    #include<stack>
    #include<string>
    #include<algorithm>
    using namespace std;
    typedef long long ll;
    const long double eps=1e-13;
    #define inf 99999999
    #define pi acos(-1.0)
    #define maxnode 500000
    struct node{
        int ch[maxnode][26];
        int val[maxnode];
        int sz,i,j,c;
        void init(){
            sz=0;
            memset(ch[0],0,sizeof(ch[0]));
            memset(val,0,sizeof(val));
        }
        int idx(char d){
            return d-'a';
        }
        void charu(char *s){
            int u=0;
            int len=strlen(s);
            for(i=0;i<len;i++){
                c=idx(s[i]);
                if(!ch[u][c]){
                    sz++;
                    memset(ch[sz],0,sizeof(ch[sz]));
                    val[sz]++;
                    ch[u][c]=sz;
                    u=ch[u][c];
                }
                else{
                    u=ch[u][c];val[u]++;
                }
            }
    
        }
        int chazhao(char *s){
            int u=0,flag=1;
            int len=strlen(s);
            for(i=0;i<len;i++){
                c=idx(s[i]);
                if(!ch[u][c]){
                    flag=0;break;
                }
                u=ch[u][c];
            }
            if(!flag)return 0;
            return val[u];
        }
    
    }tree;
    
    
    
    int main()
    {
        int n,m,i,j;
        char s[20];
        tree.init();
        while(gets(s)!=NULL && s[0]!=''){
                tree.charu(s);
        }
        while(gets(s)!=NULL){
            printf("%d
    ",tree.chazhao(s));
       }
    }
    


  • 相关阅读:
    JSP学习-10-EL表达式
    深入浅出Mybatis(一)
    第10章—开启事务
    第09章—使用Lombok插件
    第08章—整合Spring Data JPA
    第06章—热部署
    第05章—Swagger2打造在线接口文档
    第03章—打造RESTful风格API
    第04章—整合Mybatis
    第01章—快速构建
  • 原文地址:https://www.cnblogs.com/herumw/p/9464577.html
Copyright © 2020-2023  润新知