BZOJ3261: 最大異或和(可持久化trie樹)
阿新 • • 發佈:2018-10-01
while xor ble 題目 可能 [1] 節點 %d getchar()
題意
題目鏈接
Sol
設$sum[i]$表示$1 - i$的異或和
首先把每個詢問的$x \oplus sum[n]$就變成了詢問前綴最大值
可持久化Trie樹維護前綴xor,建樹的時候維護一下每個節點被遍歷了多少次
註意設置好偏移量,不然詢問區間為$[1, 1]$的時候可能掛掉
#include<bits/stdc++.h> using namespace std; const int MAXN = 6e5 + 10; inline int read() { char c = getchar(); int x = 0, f = 1; while(c < '0' || c > '9') {if(c == '-')f =- 1; c = getchar();} while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar(); return x * f; } int N, M, a[MAXN], sum[MAXN], cnt[MAXN * 25], ch[MAXN * 25][2], tot, root[MAXN]; void insert(int i, int x) { x = (sum[i] = sum[i - 1] ^ x); int p = root[i - 1], now = (root[i] = ++tot); for(int i = 23; i >= 0; i--) { bool nxt = x >> i & 1; ch[now][nxt ^ 1] = ch[p][nxt ^ 1]; now = ch[now][nxt] = ++tot; p = ch[p][nxt]; cnt[now] = cnt[p] + 1; } } int Query(int l, int r, int x) { r = root[r], l = root[l]; int ans = 0; for(int i = 23; i >= 0; i--) { int nxt = x >> i & 1; if(cnt[ch[r][nxt ^ 1]] - cnt[ch[l][nxt ^ 1]] > 0) ans += 1 << i, r = ch[r][nxt ^ 1], l = ch[l][nxt ^ 1]; else r = ch[r][nxt], l = ch[l][nxt]; } return ans; } int main() { N = read(); M = read(); for(int i = 1; i <= N; i++) a[i] = read(), insert(i, a[i]); char ss[4]; for(int i = 1; i <= M; i++) { scanf("%s", ss + 1); if(ss[1] == 'A') N++, a[N] = read(), insert(N, a[N]); else { int l = read() - 1, r = read() - 1, val = read(); printf("%d\n", Query(l - 1, r, val ^ sum[N])); } } } /* 5 5 2 6 4 3 6 A 1 Q 3 5 4 A 4 Q 5 7 0 Q 3 6 6 */
BZOJ3261: 最大異或和(可持久化trie樹)