HDU 1251 - 统计难题 ( Tire树 )

题意

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

思路

用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\n", 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;
}
posted @ 2018-08-14 15:48  JinxiSui  阅读(108)  评论(0编辑  收藏  举报