【数据结构】Trie

struct TrieNode {
    int cnt;
    int nxt[26];

    void Init() {
        cnt = 0;
        memset(nxt, 0, sizeof(nxt));
    }
};

struct Trie {

    static const int MAXN = 4000000;
    TrieNode tn[MAXN + 5];
    int root, top;

    int NewNode() {
        tn[++top].Init();
        return top;
    }

    void Init() {
        top = 0;
        root = NewNode();
    }

    void Insert(char *a, int id) {
        int n = strlen(a + 1), cur = root;
        for(int i = 1; i <= n; ++i) {
            int &nxt = tn[cur].nxt[a[i] - 'a'];
            if(!nxt)
                nxt = NewNode();
            cur = nxt;
        }
        tn[cur].cnt = id;
    }

    int Query(char *a) {
        int n = strlen(a + 1), cur = root;
        for(int i = 1; i <= n; ++i) {
            int &nxt = tn[cur].nxt[a[i] - 'a'];
            if(!nxt)
                return 0;
            cur = nxt;
        }
        return tn[cur].cnt;
    }

} trie;
posted @ 2021-01-12 04:38  purinliang  阅读(61)  评论(0编辑  收藏  举报