Codeforces Round #340 (Div. 2) E 莫队算法
@(E ACMer)
题目大意:
给你长度为
n(n<=105)
,的序列,然后
q(q<105)
个区间询问,询问该区间内有多少对
(i,j)
,让
xi xor xi+1 xor .... xor xj == k
莫队算法:
对于知道当前区间的查询结果,可以
O(1)
地知道将区间向左右增加单位长度后的结果,就可以用莫队算法。莫队算法就是:对区间查询分块排序,然后按照这个顺序,区间之间相互转移查询。那些在同一块的询问,或者相邻块的询问相互转移的花费都很小,这样只是对询问顺序进行变化,然后相互转移就可以有一个
O(n3/2)
的算法了(具体的复杂度证明我还没有考虑清楚QAQ)。
本题分析:
按照莫队算法的基本思想,只需要对add()
del()
两个函数适配具体的题型就可以了。
对于本题,值讨论区间
[l,r]
向右增加一个单位长度的转移规则,其它三种转移都类似。
- 首先将与
a[r+1]
抑或等于
k
的数:
- 然后将
a[r+1]
存在频率加加。
- 完成
注意:
- 总的区间个数会爆int
- 两个数抑或的值,可能比两个数都大
code:
#include <iostream>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
int n, q, k, a[int(1e5 +9)], cnt[int(2e6) + 9], pos[int(1e5 +9)];
int lefts, rights, block_size ;
long long ans, out[int(1e5) + 9];
struct node {
int l, r, id;
}Q[int(1e5 + 9)];
bool cmp(const node &A, const node &B) {
if (pos[A.l] == pos[B.l]) return pos[A.r] < pos[B.r];
return pos[A.l] < pos[B.l];
}
void del(int x) {
cnt[x]--;
ans -= cnt[x ^ k];
}
void add(int x) {
ans += cnt[x ^ k];
cnt[x]++;
}
int main(void)
{
// freopen("in.txt", "r", stdin);
while (cin >> n >> q >> k) {
memset(cnt, 0, sizeof(cnt));
block_size = (int)sqrt(n);
a[0] = 0;
for (int i = 1; i <= n; i++) {
cin >> a[i];
a[i] = a[i] ^ a[i - 1];
pos[i] = (i - 1) / block_size;
}
for (int i = 0; i < q; i++) {
cin >> Q[i].l >> Q[i].r;
Q[i].l--;
Q[i].id = i;
}
sort(Q, Q + q, cmp);
lefts = rights = ans = 0;
cnt[0] = 1;
for (int i = 0; i < q; i++) {
while (lefts < Q[i].l) {
del(a[lefts++]);
}
while (lefts > Q[i].l) {
add(a[--lefts]);
}
while (rights < Q[i].r) {
add(a[++rights]);
}
while (rights > Q[i].r) {
del(a[rights--]);
}
out[Q[i].id] = ans;
}
for (int i = 0; i < q; i++)
cout << out[i] << endl;
}
}