hdu1251统计难题(字典树)

hdu1251统计难题

链表版字典树:

#include <cstdio>
#include <string>
using namespace std;

class Trie
{
    Trie* next[26];
    int num;
public:
    Trie() {
        for (int i = 0; i < 26; ++i) next[i] = NULL;
        num = 0;
    }
    void insert(char *s) {
        Trie *p = this;
        for (int i = 0; s[i]; ++i) {
            int t = s[i]-'a';
            if (p->next[t] == NULL) p->next[t] = new Trie;
            p = p->next[t];
            ++ p->num;
        }
    }
    int find(char *s) {
        Trie *p = this;
        for (int i = 0; s[i]; ++i) {
            int t = s[i]-'a';
            if (p->next[t] == NULL) return 0;
            p = p->next[t];
        }
        return p->num;
    }
};
char s[11];
int main()
{
    Trie trie;
    while (gets(s), s[0]) {
        trie.insert(s);
    }
    while (gets(s)) {
        printf("%d\n", trie.find(s));
    }
    return 0;
}

数组版字典树:

为了便于封装,此处用 vector 代替了数组。

#include <cstdio>
#include <vector>
using namespace std;

class Trie
{
    int cnt;
    vector<vector<int> > tree;
    vector<int> num;
public:
    Trie(int n) {
        cnt = 0;
        tree.resize(n, vector<int>(26));
        num.resize(n);
    }
    void insert(char *s) {
        int p = 0;
        for (int i = 0; s[i]; ++i) {
            int t = s[i]-'a';
            if (!tree[p][t]) tree[p][t] = ++cnt;
            p = tree[p][t];
            ++num[p];
        }
    }
    int find(char *s) {
        int p = 0;
        for (int i = 0; s[i]; ++i) {
            int t = s[i]-'a';
            if (!tree[p][t]) return 0;
            p = tree[p][t];
        }
        return num[p];
    }
};
char s[11];
int main()
{
    Trie trie(1e6+6);
    while (gets(s), s[0]) {
        trie.insert(s);
    }
    while (gets(s)) {
        printf("%d\n", trie.find(s));
    }
    return 0;
}

posted @ 2021-03-12 23:43  Zewbie  阅读(36)  评论(0编辑  收藏  举报