zoukankan      html  css  js  c++  java
  • HDU 1251

    题意

    给出一些单词,再给出一些前缀,求有多少个单词包含这个前缀。

    思路

    用map统计水过。赛后意外的发现自己的代码跑了900+ms,为什么这么多人才跑了60+ms (滑稽)
    更好的算法是用Tire树(字典树)操作,查询前缀出现的次数,就开一个sum[],表示位置i被访问过的次数

    浅谈Trie树(字典树)

    AC代码(Tire,60+ms)

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    #include <algorithm>
    #include <cmath>
    using namespace std;
    const int maxn = 1e6+5;
    int tire[maxn][26];
    int sum[maxn];
    char str[25];
    int tot;
    
    void insert_(int len)
    {
        int x;
        int root = 0;
        for(int i = 0; i < len; i++)
        {
            x = str[i]-'a';
            if(!tire[root][x])
                tire[root][x] = ++tot;
            root = tire[root][x];
            sum[root]++;
        }
    }
    
    int find_(int len)
    {
        int root = 0;
        int x;
        for(int i = 0; i < len; i++)
        {
            x = str[i]-'a';
            if(tire[root][x] == 0) return 0;
            root = tire[root][x];
        }
        return sum[root];
    }
    
    int main()
    {
        int len;
        tot = 0;
        while( gets(str) != NULL ){
            len = strlen(str);
            if(len==0)break;
            insert_(len);
        }
        while( scanf("%s", str)!=EOF ){
            len = strlen(str);
            printf("%d
    ", find_(len));
        }
        return 0;
    }

    AC代码(map模拟,900+ms)

    #include <iostream>
    #include <algorithm>
    #include <cstdio>
    #include <cstring>
    #include <cmath>
    #include <string>
    #include <map>
    
    using namespace std;
    
    map<string, int> mp;
    string str;
    
    int main()
    {
        int len;
        while( getline(cin, str) ){
            if( str == "" ) break;
            len = (int)str.size();
            string prestr;
            for(int i = 0; i < len; i++){
                prestr += str[i];
                mp[prestr]++;
            }
        }
        while( cin >> str ){
            cout << mp[str] << endl;
        }
        return 0;
    }
  • 相关阅读:
    == 和equals方法
    ObjectInputStream 与ObjectOutputStream
    IOS基础:ObjectiveC 数组处理
    学习笔记:自定义方法的两种实现方式
    DatePicker 获取时间的时区问题
    IOS基础:tableview中cell
    IOS基础:窗口切换的几种方法
    IOS基础:ObjectiveC 字符串处理
    使用 Notifications
    学习笔记:Tab Bar 控件使用详解
  • 原文地址:https://www.cnblogs.com/JinxiSui/p/9740524.html
Copyright © 2011-2022 走看看