Templates - Data structure - Trie

Nxt pointer using a static array of design, probably as the nxt pointer than using a map designed to be twice as fast, but also a large space cost about 1 times. In the case where a small amount of data, and time and space efficiency is not map <vector ,int>。map<vector , Efficiency int> the worst case O (nlogn * len), while the efficiency of Trie is O (n * len), but actually test out a little faster or map, it is possible vector Compare actual time will soon come to size up.

Time Complexity:
Initialization: O (sigma)
insert: O (len * sigma)
query: O (len)

Space complexity:
O (n-* len * Sigma)

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

    void init() {
        data = 0;
        memset(nxt, 0, sizeof(nxt));
    }
};

struct Trie {
    TrieNode tn[200005];
    int root, top;

    int newnode() {
        tn[++top].init();
        return top;
    }

    void init() {
        top = 0;
        root = newnode();
    }

    void insert(int *a, int len, int data) {
        int cur = root;
        for(int i = 1; i <= len; ++i) {
            int &nxt = tn[cur].nxt[a[i] - 'a'];
            if(!nxt)
                nxt = newnode();
            cur = nxt;
        }
        tn[cur].data = data;
    }

    int query(int *a, int len) {
        int cur = root;
        for(int i = 1; i <= len; ++i) {
            int &nxt = tn[cur].nxt[a[i] - 'a'];
            if(!nxt)
                return -1;
            cur = nxt;
        }
        return tn[cur].data;
    }
} trie;

Guess you like

Origin www.cnblogs.com/KisekiPurin2019/p/11858431.html