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

    统计难题

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


    Problem Description
    Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).
     
    Input
    输入数据的第一部分是一张单词表,每行一个单词,单词的长度不超过10,它们代表的是老师交给Ignatius统计的单词,一个空行代表单词表的结束.第二部分是一连串的提问,每行一个提问,每个提问都是一个字符串.

    注意:本题只有一组测试数据,处理到文件结束.
     
    Output
    对于每个提问,给出以该字符串为前缀的单词的数量.
     
    Sample Input
    banana
    band
    bee
    absolute
    acm
     
     
    ba
    b
    band
    abc
     
    Sample Output
    2
    3
    1
    0
     
    Author
    Ignatius.L
     
     
     
    解析:字典树。
     
     
    (注意用C++提交)
    #include <cstdio>
    #include <cstring>
    
    const int MAX = 26;
    
    struct Node{
        Node* pt[MAX];
        int num;
    };
    Node *root;
    
    Node memory[500000];
    int allo = 0;
    
    void trie_init()
    {
        root = new Node;
        memset(root->pt, NULL, sizeof(root->pt));
    }
    
    void trie_insert(char str[])
    {
        Node *p = root, *q;
        for(int i = 0; str[i] != ''; ++i){
            int id = str[i]-'a';
            if(p->pt[id] == NULL){
                q = &memory[allo++];
                memset(q->pt, NULL, sizeof(q->pt));
                q->num = 1;
                p->pt[id] = q;
            }
            else{
                ++p->pt[id]->num;
            }
            p = p->pt[id];
        }
    }
    
    int trie_find(char str[])
    {
        Node *p = root;
        for(int i = 0; str[i] != ''; ++i){
            int id = str[i]-'a';
            if(p->pt[id] == NULL){
                return 0;
            }
            p = p->pt[id];
        }
        return p->num;
    }
    
    int main()
    {
        char s[15];
        trie_init();
        while(gets(s) && s[0]){
            trie_insert(s);
        }
        while(gets(s)){
            printf("%d
    ", trie_find(s));
        }
        return 0;
    }
    

      

    用map很耗时,但本题刚好可以卡过去。

    #include <cstdio>
    #include <string>
    #include <cstring>
    #include <map>
    using namespace std;
    
    map<string, int> mp;
    
    int main()
    {
        char s[15];
        while(gets(s) && s[0]){
            int len = strlen(s);
            for(int i = len; i > 0; --i){
                s[i] = '';
                ++mp[s];
            }
        }
        while(gets(s)){
            printf("%d
    ", mp[s]);
        }
        return 0;
    }
    

      

  • 相关阅读:
    GLUT Tutorials 9: GLUT子菜单
    GLUT Tutorials 8: GLUT菜单
    GLUT Tutorials 9: GLUT鼠标
    GLUT Tutorials 8: GLUT高级键盘控制
    GLUT Tutorials 7: GLUT高级键盘控制
    GLUT Tutorials 6: GLUT场景漫游
    gif 录制小工具
    GLUT Tutorials 5: GLUT键盘控制
    java 传址或传值
    java中如何将byte[]里面的数据转换成16进制字符串
  • 原文地址:https://www.cnblogs.com/inmoonlight/p/5906532.html
Copyright © 2011-2022 走看看