字典树(Trie)学习笔记

· · 算法·理论

字典树是一种可以用 O(len) 的时间查找一个字符串的存在/个数/对应的值的数据结构,大概长这样:

模板:

struct Node {
    char c;
    unordered_map<ll, ll> cld;
    ll prx = 0, cnt = 0; // 该字符串作为前缀的次数,该字符串的个数
};
struct Trie {
    ll size = 1;
    vector<Node> a = vector<Node>(2);
    ll cd(char x) {
        return x - 'a' + 1;
    }
    void insert(string& x) {
        ll pos = 1, p = 0;
        while (p < x.size()) {
            if (a[pos].cld[cd(x[p])] == 0) {
                a.push_back(Node());
                a[pos].cld[cd(x[p])] = ++size;
            }
            a[pos].prx++;
            pos = a[pos].cld[cd(x[p])];
            a[pos].c = x[p++];
        }
        a[pos].prx++;
        a[pos].cnt++;
    }
    ll qry(string& x) { // 查找一个字符串作为前缀的次数
        ll pos = 1, p = 0;
        while (p < x.size()) {
            if (a[pos].cld[cd(x[p])] == 0) {
                return 0;
            }
            pos = a[pos].cld[cd(x[p])];
            p++;
        }
        return a[pos].prx;
    }
};

例题:

其实可以用哈希做

查找一个字符串作为前缀的个数。

#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
typedef long long ll;

struct Node {
    char c;
    unordered_map<ll, ll> cld;
    ll prx = 0, cnt = 0;
};
struct Trie {
    ll size = 1;
    vector<Node> a = vector<Node>(2);
    ll cd(char x) {
        if ('a' <= x && x <= 'z') {
            return x - 'a' + 1;
        } else if ('A' <= x && x <= 'Z') {
            return x - 'A' + 27;
        } else if ('0' <= x && x <= '9') {
            return x - '0' + 53;
        }
    }
    void insert(string& x) {
        ll pos = 1, p = 0;
        while (p < x.size()) {
            if (a[pos].cld[cd(x[p])] == 0) {
                a.push_back(Node());
                a[pos].cld[cd(x[p])] = ++size;
            }
            a[pos].prx++;
            pos = a[pos].cld[cd(x[p])];
            a[pos].c = x[p++];
        }
        a[pos].prx++;
        a[pos].cnt++;
    }
    ll qry(string& x) {
        ll pos = 1, p = 0;
        while (p < x.size()) {
            if (a[pos].cld[cd(x[p])] == 0) {
                return 0;
            }
            pos = a[pos].cld[cd(x[p])];
            p++;
        }
        return a[pos].prx;
    }
};

ll T, n, q;

int main() {
    cin >> T;
    while (T--) {
        Trie a;
        cin >> n >> q;
        for (ll i = 1; i <= n; i++) {
            string tmp;
            cin >> tmp;
            a.insert(tmp);
        }
        for (ll i = 1; i <= q; i++) {
            string tmp;
            cin >> tmp;
            cout << a.qry(tmp) << endl;
        }
    }
    return 0;
}

其实可以用哈希做

存储一个名字在名单上出现的次数与被点的次数之和即可。

#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
typedef long long ll;

struct Node {
    char c;
    unordered_map<ll, ll> cld;
    ll prx = 0, cnt = 0;
};
struct Trie {
    ll size = 1;
    vector<Node> a = vector<Node>(2);
    ll cd(char x) {
        return x - 'a' + 1;
    }
    void insert(string& x) {
        ll pos = 1, p = 0;
        while (p < x.size()) {
            a[pos].prx++;
            if (a[pos].cld[cd(x[p])] == 0) {
                a.push_back(Node());
                a[pos].cld[cd(x[p])] = ++size;
            }
            pos = a[pos].cld[cd(x[p])];
            a[pos].c = x[p];
            p++;
        }
        a[pos].prx++;
        a[pos].cnt++;
    }
    ll qry(string& x) {
        ll pos = 1, p = 0;
        while (p < x.size()) {
            if (a[pos].cld[cd(x[p])] == 0) {
                return 0;
            }
            pos = a[pos].cld[cd(x[p])];
            p++;
        }
        return a[pos].cnt++;
    }
} t;

ll n, m;

int main() {
    cin >> n;
    while (n--) {
        string tmp;
        cin >> tmp;
        t.insert(tmp);
    }
    cin >> m;
    while (m--) {
        string tmp;
        cin >> tmp;
        ll q = t.qry(tmp);
        if (q == 0) {
            cout << "WRONG" << endl;
        } else if (q == 1) {
            cout << "OK" << endl;
        } else {
            cout << "REPEAT" << endl;
        }
    }
    return 0;
}

其实可以用哈希做

对于每个单词,存储它在哪几篇文章中出现过即可,注意去重。

#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
typedef long long ll;

struct Node {
    char c;
    unordered_map<ll, ll> cld;
    ll prx = 0, cnt = 0;
    vector<ll> psg;
};
struct Trie {
    ll size = 1;
    vector<Node> a = vector<Node>(2);
    ll cd(char c) {
        return c - 'a' + 1;
    }
    void insert(string& x, ll psgno) {
        ll pos = 1, p = 0;
        while (p < x.size()) {
            a[pos].prx++;
            if (a[pos].cld[cd(x[p])] == 0) {
                a.push_back(Node());
                a[pos].cld[cd(x[p])] = ++size;
            }
            pos = a[pos].cld[cd(x[p])];
            a[pos].c = x[p];
            p++;
        }
        a[pos].prx++;
        a[pos].cnt++;
        if (a[pos].psg.empty() || a[pos].psg[a[pos].psg.size() - 1] < psgno) {
            a[pos].psg.push_back(psgno);
        }
    }
    vector<ll> qry(string& x) {
        ll pos = 1, p = 0;
        while (p < x.size()) {
            if (a[pos].cld[cd(x[p])] == 0) {
                return vector<ll>();
            }
            pos = a[pos].cld[cd(x[p])];
            p++;
        }
        return a[pos].psg;
    }
} t;

ll n, l, m;

int main() {
    cin >> n;
    for (ll i = 1; i <= n; i++) {
        cin >> l;
        while (l--) {
            string tmp;
            cin >> tmp;
            t.insert(tmp, i);
        }
    }
    cin >> m;
    while (m--) {
        string tmp;
        cin >> tmp;
        vector<ll> p = t.qry(tmp);
        for (ll i : p) {
            cout << i << " ";
        }
        cout << endl;
    }
    return 0;
}

其实可以用哈希做

查询有多少个01串是他的前缀,以及它作为前缀的数量

#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
typedef long long ll;

struct Node {
    ll c;
    unordered_map<ll, ll> cld;
    ll prx = 0, cnt = 0;
};
struct Trie {
    ll size = 1;
    vector<Node> a = vector<Node>(2);
    void insert(vector<ll>& x) {
        ll pos = 1, p = 0;
        while (p < x.size()) {
            a[pos].prx++;
            if (a[pos].cld[x[p]] == 0) {
                a.push_back(Node());
                a[pos].cld[x[p]] = ++size;
            }
            pos = a[pos].cld[x[p]];
            a[pos].c = x[p];
            p++;
        }
        a[pos].prx++;
        a[pos].cnt++;
    }
    ll qry(vector<ll>& x) {
        ll pos = 1, p = 0, r = 0;
        while (p < x.size()) {
            if (a[pos].cld[x[p]] == 0) {
                return r;
            }
            pos = a[pos].cld[x[p]];
            p++;
            r += a[pos].cnt;
        }
        r += a[pos].prx;
        r -= a[pos].cnt;
        return r;
    }
} t;

ll m, n, l;

int main() {
    cin >> m >> n;
    while (m--) {
        cin >> l;
        vector<ll> tmp;
        while (l--) {
            ll tmp1;
            cin >> tmp1;
            tmp.push_back(tmp1);
        }
        t.insert(tmp);
    }
    while (n--) {
        cin >> l;
        vector<ll> tmp;
        while (l--) {
            ll tmp1;
            cin >> tmp1;
            tmp.push_back(tmp1);
        }
        cout << t.qry(tmp) << endl;
    }
    return 0;
}

在插入每个词的时候记录该单词有多少个前缀在之前插入过的单词中,同时更新答案即可。

#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
typedef long long ll;

const ll inf = 0x3f3f3f3f3f3f3f3f;

ll ans = ~inf;

struct Node {
    char c;
    unordered_map<char, ll> cld;
    ll prx = 0, cnt = 0, wc = 0;
};
struct Trie {
    ll size = 1;
    vector<Node> a = vector<Node>(2);
    void insert(string& x) {
        ll pos = 1, p = 0, wc = 0;
        while (p < x.size()) {
            a[pos].prx++;
            if (a[pos].cld[x[p]] == 0) {
                a.push_back(Node());
                a[pos].cld[x[p]] = ++size;
            }
            pos = a[pos].cld[x[p]];
            wc += a[pos].cnt;
            a[pos].c = x[p];
            if (p == x.size() - 1) {
                a[pos].wc = wc + 1;
            }
            p++;
        }
        a[pos].prx++;
        a[pos].cnt++;
        ans = max(ans, a[pos].wc);
    }
} t;

ll n;

int main() {
    cin >> n;
    while (n--) {
        string tmp;
        cin >> tmp;
        t.insert(tmp);
    }
    cout << ans << endl;
    return 0;
}

不难想到递推:令 d_i 为长单词(记为 p )的前 i 个字符的分解方法数,则有 d_i=\operatorname{sum}\{d_j | 1\le j\le i\operatorname{and}p_{[j+1,i]} 在字典中 \} ,可以枚举字典中的每个单词是不是 p_{[1,i]} 的后缀,想到字典树维护。还可以令 d_i 为 p 的后 i 个字符的分解方法数,这样子要查找的就是前缀。

字典树结合图搜

将所有的字符串倒着加入即可,注意维护树中字符串的数量,之前的字符串是这个的前缀的时候要将之前的字符串删除,以及处理字符串末尾的\0.

#include <iostream>
#include <unordered_map>
#include <vector>
typedef long long ll;
using namespace std;

string rev(string& x) {
    string r;
    for (char c : x) {
        r = c + r;
    }
    return r;
}
struct Node {
    char c;
    ll prx = 0, cnt = 0;
    unordered_map<char, ll> cld;
};
struct Trie {
    ll size = 1, cnt = 0;
    vector<Node> val = vector<Node>(2);
    void insert(string& x) {
        ll pos = 1, p = 0;
        while (p < x.size()) {
            val[pos].prx++;
            if (val[pos].cld[x[p]] == 0) {
                val.push_back(Node());
                val[pos].cld[x[p]] = ++size;
            }
            if (val[pos].cnt) {
                cnt--;
                val[pos].cnt--;
            }
            pos = val[pos].cld[x[p]];
            val[pos].c = x[p];
            p++;
        }
        if (!val[pos].prx) {
            cnt++;
            val[pos].cnt++;
        }
        val[pos].prx++;
    }
    void qry(vector<string>& ans, string crt, ll pos) {
        if (pos == 0) {
            return;
        }
        crt += val[pos].c;
        if (val[pos].cnt == 1) {
            ans.push_back(crt);
            return;
        }
        for (char i = '0'; i <= '9'; i++) {
            if (val[pos].cld[i] == 0) {
                continue;
            }
            qry(ans, crt, val[pos].cld[i]);
        }
    }
};
unordered_map<string, Trie> fr;

ll n;

string ds(string& x) {
    string r;
    for (char c : x) {
        if ('0' <= c && c <= '9') {
            r += c;
        }
    }
    return r;
}

int main() {
    cin >> n;
    for (ll i = 1; i <= n; i++) {
        ll m;
        string tmp, tmp1;
        cin >> tmp >> m;
        while (m--) {
            cin >> tmp1;
            tmp1 = ds(tmp1);
            tmp1 = rev(tmp1);
            fr[tmp].insert(tmp1);
        }
    }
    cout << fr.size() << endl;
    for (auto i : fr) {
        cout << i.first << " " << i.second.cnt << " ";
        vector<string> ans;
        i.second.qry(ans, string(), 1);
        for (string j : ans) {
            j = rev(j);
            cout << ds(j) << " ";
        }
        cout << endl;
    }
    return 0;
}

在检查时使用递归函数,将是否存在有一位不同作为参数传入,然后在树上搜索即可。

#include <iostream>
#include <vector>
typedef long long ll;
using namespace std;

struct Node {
    char c;
    ll cld[3] = {};
    ll prx = 0, cnt = 0;
};
struct Trie {
    ll size = 1;
    vector<Node> val = vector<Node>(2);
    ll cd(char x) {
        return x - 'a';
    }
    void insert(string& x) {
        ll pos = 1, p = 0;
        while (p < x.size()) {
            val[pos].prx++;
            if (val[pos].cld[cd(x[p])] == 0) {
                val.push_back(Node());
                val[pos].cld[cd(x[p])] = ++size;
            }
            pos = val[pos].cld[cd(x[p])];
            val[pos].c = x[p];
            p++;
        }
        val[pos].prx++;
        val[pos].cnt++;
    }
    bool chk(string& x, ll pos, ll p, bool dif) {
        if (pos == 0) {
            return 0;
        }
        if (p >= x.size()) {
            if (dif && val[pos].cnt) {
                return 1;
            } else {
                return 0;
            }
        }
        if (dif) {
            if (chk(x, val[pos].cld[cd(x[p])], p + 1, 1)) {
                return 1;
            }
        } else {
            for (ll i = 0; i < 3; i++) {
                if (i + 'a' == x[p]) {
                    if (chk(x, val[pos].cld[i], p + 1, 0)) {
                        return 1;
                    }
                } else {
                    if (chk(x, val[pos].cld[i], p + 1, 1)) {
                        return 1;
                    }
                }
            }
        }
        return 0;
    }
} t;

ll n, m;

int main() {
    cin >> n >> m;
    while (n--) {
        string tmp;
        cin >> tmp;
        t.insert(tmp);
    }
    while (m--) {
        string tmp;
        cin >> tmp;
        if (t.chk(tmp, 1, 0, 0)) {
            cout << "YES" << endl;
        } else {
            cout << "NO" << endl;
        }
    }
    return 0;
} 

字典树维护位运算(又称01-Trie)

即存储每个数的二进制,方便进行位运算(大多数时候是异或)。

枚举 x,利用01-Trie和贪心(某一位上是 1 的大过某一位上是 0 的,所以如果 k 的这一位是 1,则可以将全部和 x 异或后这一位为 0 的计入)计算答案。以及这道题卡unordered_map常数。

#include <iostream>
#include <algorithm>
#include <unordered_map>
#include <vector>
using namespace std;
typedef long long ll;

const ll inf = 0x3f3f3f3f3f3f3f3f, MAXX = 1048576;

struct Node {
    ll c, cld[2] = {};
    ll prx = 0, cnt = 0;
};
struct Trie {
    ll size = 1;
    vector<Node> a = vector<Node>(2);
    void insert(ll x) {
        ll pos = 1, p = MAXX;
        while (p) {
            a[pos].prx++;
            ll dig = x >= p;
            if (dig) {
                x -= p;
            }
            if (a[pos].cld[dig] == 0) {
                a.push_back(Node());
                a[pos].cld[dig] = ++size;
            }
            pos = a[pos].cld[dig];
            a[pos].c = dig;
            p /= 2;
        }
        a[pos].prx++;
        a[pos].cnt++;
    }
    ll qry(ll x, ll k) {
        ll pos = 1, p = MAXX, r = 0;
        while (p) {
            ll xdig = x >= p;
            ll kdig = k >= p;
            if (kdig == 0) {
                pos = a[pos].cld[xdig];
            } else {
                r += a[a[pos].cld[xdig]].prx;
                pos = a[pos].cld[!xdig];
            }
            if (pos == 0) {
                break;
            }
            if (xdig) {
                x -= p;
            }
            if (kdig) {
                k -= p;
            }
            p /= 2;
        }
        r += a[pos].cnt;
        return r;
    }
} t;

ll n, k, ans = ~inf;

int main() {
    cin >> n >> k;
    for (ll i = 1, tmp; i <= n; i++) {
        cin >> tmp;
        t.insert(tmp);
    }
    for (ll i = 0; i < MAXX; i++) {
        ans = max(ans, t.qry(i, k));
    }
    cout << ans << endl;
    return 0;
}

将每个点到根的异或路径加入01-Trie中,然后求树中两个数的最大异或值即可。

#include <iostream>
#include <vector>
typedef long long ll;
using namespace std;

const ll MAXW = 2147483648, MAXN = 100000;

struct Edge {
    ll to, val;
    Edge(ll x, ll y) {
        to = x;
        val = y;
    }
    Edge() {}
};

struct TrieNode {
    ll c, cld[2] = {}, prx = 0, cnt = 0;
};
struct Trie {
    ll size = 1;
    vector<TrieNode> val = vector<TrieNode>(2);
    void insert(ll x) {
        ll pos = 1, p = MAXW;
        while (p) {
            val[pos].prx++;
            ll dig = x >= p;
            if (val[pos].cld[dig] == 0) {
                val.push_back(TrieNode());
                val[pos].cld[dig] = ++size;
            }
            pos = val[pos].cld[dig];
            val[pos].c = dig;
            if (dig) {
                x -= p;
            }
            p /= 2;
        }
    }
    ll cal(ll pos1, ll pos2, ll p, ll xorval) {
        if (p == 0) {
            return xorval;
        }
        if (pos1 == 0 || pos2 == 0) {
            return 0;
        }
        ll dig = 0, r = 0;
        if (val[pos1].cld[0] && val[pos2].cld[1]) {
            r = max(r, cal(val[pos1].cld[0], val[pos2].cld[1], p / 2, xorval + p));
            dig = 1;
        }
        if (val[pos1].cld[1] && val[pos2].cld[0]) {
            r = max(r, cal(val[pos1].cld[1], val[pos2].cld[0], p / 2, xorval + p));
            dig = 1;
        }
        if (!dig) {
            if (val[pos1].cld[1] && val[pos2].cld[1]) {
                r = max(r, cal(val[pos1].cld[1], val[pos2].cld[1], p / 2, xorval));
            }
            if (val[pos1].cld[0] && val[pos2].cld[0]) {
                r = max(r, cal(val[pos1].cld[0], val[pos2].cld[0], p / 2, xorval));
            }
        }
        return r;
    }
} t;

ll n, p[MAXN + 5] = {}, xv[MAXN + 5] = {};
vector<Edge> e[MAXN + 5];

void init_p(ll x, ll pr) {
    p[x] = pr;
    for (auto i : e[x]) {
        if (i.to == pr) {
            continue;
        }
        init_p(i.to, x);
    }
}

void init_trie(ll x, ll xorval) {
    t.insert(xorval);
    xv[x] = xorval;
    for (auto i : e[x]) {
        if (i.to == p[x]) {
            continue;
        }
        init_trie(i.to, xorval ^ i.val);
    }
}

int main() {
    cin >> n;
    for (ll i = 1, u, v, w; i <= n - 1; i++) {
        cin >> u >> v >> w;
        e[u].push_back(Edge(v, w));
        e[v].push_back(Edge(u, w));
    }
    init_p(1, 0);
    init_trie(1, 0);
    cout << t.cal(1, 1, MAXW, 0) << endl;
    return 0;
}