字典树 检索字符串 维护异或极值

字典树

字典树维护字符串

根结点编号为 1 1 1 ,字典树用边代表某个字母,从根结点到某一个结点的路径就代表一个字符串(用 c n t [ i ] cnt[i] cnt[i]​​ 来维护这个点是不是字符串的结尾以及这个字符串的数量)。

一个结构体封装的模板

struct Trie {
    
    
    int son[maxn][26], idx = 1, cnt[maxn]; // 根结点下标为1
    void insert(char s[]) {
    
      // 插入字符串
        int p = 1;
        for (int i = 1; s[i]; i++) {
    
    
            int c = s[i] - 'a';
            if (!son[p][c]) son[p][c] = ++idx;  // 如果没有,就添加结点
            p = son[p][c];
        }
        cnt[p]++;
    }
    int query(char s[]) {
    
      // 查找字符串
        int p = 1;
        for (int i = 1; s[i]; i++) {
    
    
            int c = s[i] - 'a';
            if (!son[p][c]) return 0;
            p = son[p][c];
        }
        return cnt[p];
    }
} tire;

字典树维护异或极值

把一个整数用二进制表示,字典树的边代表一位二进制,用字典树来维护 n n n​ 个数,对每个数询问异或最大值,贪心的从高位到低位走,对应树上从根到叶子结点,不需要标记某个结点是不是结尾,结尾一定是深度相同的叶子结点。

用结构体封装的模版:

struct Trie {
    
    
    int son[maxn * 32][2], idx = 1;
    void insert(int x) {
    
    
        int p = 1;
        for (int i = 30; ~i; --i) {
    
    
            int &s = son[p][x >> i & 1];
            if (!s) s = ++idx;
            p = s;
        }
    }
    int query(int x) {
    
    
        int res = 0, p = 1;
        for (int i = 30; ~i; --i) {
    
    
            int s = x >> i & 1;
            if (son[p][!s]) {
    
    
                res += 1 << i;
                p = son[p][!s];
            } else p = son[p][s];
        }
        return res;
    }
} Trie;

猜你喜欢

转载自blog.csdn.net/weixin_43860866/article/details/119183290