HDU1251 统计难题 题解 字典树

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1251

题目大意:给你若干模式串,以及若干询问,每次询问给你一个字符串,问该字符串可以作为多少个模式串的前缀。

解题思路:使用字典树,插入的时候每个点cnt++,查询的时候查询最终点的cnt即可。

实现代码如下:

#include <bits/stdc++.h>
using namespace std;
const int maxn = 1000010;
struct Trie {
    int son[26], cnt;
    Trie() {
        memset(son, 0, sizeof(son));
        cnt = 0;
    }
} trie[maxn];
int sz;
void Insert(char *s) {
    if (sz == 0) trie[++sz] = Trie();
    int x = 1;
    while (*s) {
        int id = *s - 'a';
        if (!trie[x].son[id]) {
            trie[++sz] = Trie();
            trie[x].son[id] = sz;
        }
        x = trie[x].son[id];
        trie[x].cnt ++;
        s ++;
    }
}
int get(char *s) {
    int x = 1;
    while (*s) {
        int id = *s - 'a';
        if (!trie[x].son[id]) return 0;
        x = trie[x].son[id];
        s ++;
    }
    return trie[x].cnt;
}
char s[110];
int main() {
    while (gets(s) && s[0]) Insert(s);
    while (gets(s)) cout << get(s) << endl;
    return 0;
}
posted @ 2020-03-22 22:42  quanjun  阅读(95)  评论(0编辑  收藏  举报