相似於超級鋼琴,咱們用堆維護一個四元組\((st, l, r, pos)\)表示以\(st\)爲起點,終點在\([l, r]\)內,裏面的最大值的位置爲\(pos\)node
咱們維護一個小根堆(堆頂最大),權值爲st-pos的異或和,每一次找出最大的並刪掉c++
所謂刪,就是把一個區間從pos處分裂spa
即:\((st, l, r)->(st, l, pos - 1) (st, pos + 1, r)\)debug
這樣從新維護pos值便可code
維護pos值時,咱們須要維護區間內與x的異或值最大,不難想到可持久化\(Trie\),因而只須要把超級鋼琴中的\(RMQ\)變成可持久化\(Trie\)便可get
#include<bits/stdc++.h> using namespace std; #define il inline #define re register #define debug printf("Now is Line : %d\n",__LINE__) #define file(a) freopen(#a".in","r",stdin);freopen(#a".out","w",stdout) #define ll long long il ll read() { re ll x = 0, f = 1; re char c = getchar(); while(c < '0' || c > '9') { if(c == '-') f = -1; c = getchar();} while(c >= '0' && c <= '9') x = x * 10 + c - 48, c = getchar(); return x * f; } #define rep(i, s, t) for(re int i = s; i <= t; ++ i) #define maxn 500005 int n, m; ll sum[maxn], ans; namespace Trie { struct PAX { int id, s, ch[2]; }e[maxn * 50]; int cnt, rt[maxn]; il void insert(int&k, int kk, int bit, int id, ll val) { k = ++ cnt; e[k] = e[kk], ++ e[k].s; if(bit == -1) return(void)(e[k].id = id); int c = (val >> bit) & 1; insert(e[k].ch[c], e[kk].ch[c], bit - 1, id, val); } il int query(int l, int r, int bit, ll val) { if(bit == -1) return e[r].id; int c = (val >> bit) & 1; if(e[e[r].ch[c ^ 1]].s > e[e[l].ch[c ^ 1]].s) return query(e[l].ch[c ^ 1], e[r].ch[c ^ 1], bit - 1, val); return query(e[l].ch[c], e[r].ch[c], bit - 1, val); } } using namespace Trie; struct node { int st, l, r, pos; il bool operator < (const node a) const { return (sum[pos] ^ sum[st - 1]) < (sum[a.pos] ^ sum[a.st - 1]); } node(int St, int L, int R) { st = St, l = L, r = R, pos = query(rt[l - 1], rt[r], 32, sum[st - 1]); } }; priority_queue<node>q; signed main() { file(a); n = read(), m = read(); rep(i, 1, n) sum[i] = sum[i - 1] ^ read(); rep(i, 1, n) insert(rt[i], rt[i - 1], 32, i, sum[i]); rep(i, 1, n) q.push(node(i, i, n)); while(m --) { node t = q.top(); q.pop(); ans += sum[t.pos] ^ sum[t.st - 1]; if(t.l < t.pos) q.push(node(t.st, t.l, t.pos - 1)); if(t.pos < t.r) q.push(node(t.st, t.pos + 1, t.r)); } printf("%lld", ans); return 0; }