模板 - 字典树

字典树Trie,指针版本的实现。要是需要改成动态的也很简单,只要把NewNode改一下就可以了。

const int MAXN = 500000;

struct TrieNode {
    TrieNode *ch[10];
};

struct Trie {
    TrieNode tn[MAXN + 5], *root;
    int top;

    inline void Init() {
        top = 0;
        root = NewNode();
    }
    inline TrieNode *NewNode() {
        for(int i = 0; i < 10; ++i)
            tn[top].ch[i] = nullptr;
        return &tn[top++];
    }
    inline TrieNode *Insert(char *s) {
        TrieNode *cur = root, *next;
        for(char *i = s; *i != '\0'; ++i) {
            next = cur->ch[*i - '0'];
            if(!next)
                next = NewNode();
            cur = next;
        }
        return cur;
    }
    inline TrieNode *Query(char *s) {
        TrieNode *cur = root, *next;
        for(char *i = s; *i != '\0'; ++i) {
            next = cur->ch[*i - '0'];
            if(!next)
                return nullptr;
            cur = next;
        }
        return cur;
    }
} trie;

猜你喜欢

转载自www.cnblogs.com/Yinku/p/11247784.html