ZTL — 数据结构 — Trie

struct Trie{
    int ch[maxn][26], val[maxn], cnt;
    Trie(){
        cnt = 1;
        memset(ch[0],0,sizeof(ch[0]));
        memset(val,0,sizeof(val));
    }
    int cti(char ch){return ch-'a'}
    void insert(char *s, int v){
        int u = 0, len = strlen(s+1);
        for(int i = 1; i <= len; ++i){
            int c = cti(s[i]);
            if(!ch[u][c]){
                memset(ch[sz],0,sizeof(ch[sz]));
                val[cnt] = 0;
                ch[u][c] = cnt++;
            }
            u = ch[u][c];
        }
        val[u] = v;
    }
    int search(char *s){
        int u = 0, len = strlen(s+1);
        for(int i = 1; i <= len; ++i){
            int c = cti(s[i]);
            if(!ch[u][c]) return -1;
            u = ch[u][c];
        }
        return val[u];
    }
}trie;

异或版(一般trie虽然叫字典树,但更多地还是维护异或吧……)

struct Trie{
    int ch[maxn<<5][2], val[maxn], cnt;
    Trie(){
        cnt = 1;
        memset(ch[0],0,sizeof(ch[0]));
    }
    inline void insert(int x){
        bool tmp; int now = 0;
        for(int i = (1<<30); i; i >>= 1){
            tmp = x & i;
            if(!ch[now][tmp]) ch[now][tmp] = cnt++;
            now = ch[now][tmp];
        }
    }
    inline int search(int x){
        int u = 0, ans = 0; bool c;
        for(int i = (1<<30); i; i >>= 1){
            c = x & i;
            if(ch[u][!c]){
                u = ch[u][!c];
                ans += i;
            }else u = ch[u][c];
        }
        return ans;
    }
}trie;
posted @ 2020-11-05 20:29  zimindaada  阅读(105)  评论(0编辑  收藏  举报