模板 - 字典树

字典树Trie,还是数组的好,草。

const int MAXN = 500000;

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

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;
        for(char *i = s; *i != '\0'; ++i) {
            TrieNode *(&next)=cur->ch[*i - 'a'];
            if(!next)
                next = NewNode();
            cur = next;
        }
        return cur;
    }
    inline TrieNode *Query(char *s) {
        TrieNode *cur = root;
        for(char *i = s; *i != '\0'; ++i) {
            TrieNode *(&next)=cur->ch[*i - 'a'];
            if(!next)
                return nullptr;
            cur = next;
        }
        return cur;
    }
} trie;
const int MAXN = 5000000;

struct TrieNode {
    int ch[26];
};

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

    inline void Init() {
        top = 0;
        root = NewNode();
    }
    inline int NewNode() {
        memset(tn[top].ch,0,sizeof(tn[top].ch));
        return top++;
    }
    inline int Insert(char *s) {
        int cur = root;
        for(char *i = s; *i != '\0'; ++i) {
            int t=*i - 'a';
            if(!tn[cur].ch[t])
                tn[cur].ch[t] = NewNode();
            cur = tn[cur].ch[t];
        }
        return cur;
    }
    inline bool Query(char *s) {
        int cur = root;
        for(char *i = s; *i != '\0'; ++i) {
            int t=*i - 'a';
            if(!tn[cur].ch[t])
                return false;
            cur = tn[cur].ch[t];
        }
        return true;
    }
} trie;
posted @ 2019-07-26 00:09  韵意  阅读(117)  评论(0编辑  收藏  举报