[Codeforces 842D Vitya and Strange Lesson]異或字典樹

[Codeforces 842D Vitya and Strange Lesson]異或字典樹

分類:Data Structure Trie Tree

1. 題目鏈接

[Codeforces 842D Vitya and Strange Lesson]

2. 題意描述

N 個數,M 次查詢a1,a2,,an 。每次查詢包含一個數x ,將所有數與x 異或,即ai=aix 。然後求出mex{a1,a2,,an} 。注意,當前操作會改變原數組。
mex{a1,a2,,an} 表示除a1,a2,,an 之外的最小非負數。

3. 解題思路

首先,第i 次詢問,可以看成是與前面所有詢問的疊加。因爲是異或操作,只需要去一個前綴異或值就好了。
對輸入的a1,a2,,an 建立一棵二叉字典樹,並判斷每個節點下的子樹是否滿了。那麼對於每個詢問,從二進制高位向低位遍歷整個樹,假如當前位爲j(j{0,1}) ,那麼j==0 就判斷左兒子子樹是否滿,否則判斷右兒子子樹是否滿。如果滿,就走另外一棵子樹。邊走邊計算答案就好了。

4. 實現代碼

#include <bits/stdc++.h>
using namespace std;

const int MAXN = 3e5 + 5;
const int MAXB = 20;

int n, m, a[MAXN];
struct Trie {
    struct TNode {
        int ch[2];
        bool full;
        void init() { full = false; ch[0] = ch[1] = 0; }
    } nd[MAXN * MAXB];
    int tot, Root;
    void init() {
        memset(nd, 0, sizeof(nd));
        Root = tot = 1;
    }
    int newNode() {
        nd[tot + 1].init();
        return ++ tot;
    }
    void ins(int x) {
        int pos = Root;
        for(int i = MAXB; i >= 0; --i) {
            int j = x >> i & 1;
            if(!nd[pos].ch[j]) nd[pos].ch[j] = newNode();
            pos = nd[pos].ch[j];
        }
    }
    int getAns(int y) {
        int pos = Root, ret = 0;
        for(int i = MAXB; i >= 0; --i) {
            ret = ret << 1;
            int j = y >> i & 1;
            if(!pos) continue;
            if(nd[nd[pos].ch[j]].full == false) pos = nd[pos].ch[j], ret |= 0;
            else pos = nd[pos].ch[j ^ 1], ret |= 1;
        }
        return ret;
    }

    void dfs(int u) {
        if(!nd[u].ch[0] && !nd[u].ch[1]) {
            nd[u].full = true;
            return;
        }
        nd[u].full = true;
        for(int i = 0; i < 2; ++i) {
            if(!nd[u].ch[i]) {
                nd[u].full = false;
                continue;
            }
            dfs(nd[u].ch[i]);
            nd[u].full &= nd[nd[u].ch[i]].full;
        }
    }
} trie;

int main() {
#ifdef ___LOCAL_WONZY___
    freopen ("input.txt", "r", stdin);
#endif // ___LOCAL_WONZY___
    while(~scanf("%d %d", &n, &m)) {
        trie.init();
        for(int i = 1; i <= n; ++i) {
            scanf("%d", &a[i]);
            trie.ins(a[i]);
        }
        int x, y = 0, ans;
        trie.dfs(trie.Root);
        while(m --) {
            scanf("%d", &x); y ^= x;
            ans = trie.getAns(y);
            printf("%d\n", ans);
        }
    }
#ifdef ___LOCAL_WONZY___
    cout << "Time elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC * 1000 << " ms." << endl;
#endif // ___LOCAL_WONZY___
    return 0;
}
發佈了287 篇原創文章 · 獲贊 347 · 訪問量 45萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章