HDU

有很多单词(只有小写字母组成,不会有重复的单词出现)

要统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).

每个单词长度不会超过10.

Trie树的模板题。这个题内存把控不好容易MLE。

经过某一个节点就记一下插入时经过的次数。那么最后判断一个前缀的时候就看前缀是否能够存在。

如果存在,答案就是最后走到的这个位置记录的数字。

如果不存在,答案就是 0.

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <cstring>
using namespace std;
#define maxn 1000000 + 10
#define sigma_size 27
#define LL long long
#define INF 0x3f3f3f3f

int tot = 0;
int trie[maxn][sigma_size], sum[maxn];

void insert(char s[])
{
        int root = 0;
        for (int i = 0; s[i]; i++)
        {
                int id = s[i]-'a';
                if (!trie[root][id])
                        trie[root][id] = ++tot;
                root = trie[root][id];
                sum[root]++;
        }
}

int found(char s[])
{
        int root = 0;
        for (int i = 0; s[i]; i++)
        {
                int id = s[i]-'a';
                if (!trie[root][id])
                        return 0;
                root = trie[root][id];
        }
        return sum[root];
}

int main()
{
        char s[11];
        while(gets(s))
        {
                if (s[0] == 0) break;
                insert(s);
        }

        while(scanf("%s", s) != EOF)
                printf("%d
", found(s));
}
原文地址:https://www.cnblogs.com/ruthank/p/9461463.html