Gravatar
终焉折枝
积分:1433
提交:193 / 351

Pro4291  [CQOI2018] 异或序列


更好的阅读体验:https://www.cnblogs.com/To-Carpe-Diem/p/19555727


大意

求一段区间 $[l, r]$ 里面的 $(i, j)$ 二元组,满足 $s[i] \oplus s[i + 1] \cdots \oplus s[j] = k$。


思路

首先,我们不难想到这个异或的性质可以扩展,然后,我们可以考虑用莫队求解此题。

对于询问分块,那我们只需要考虑加入一个点与删除一个点对 $ans$ 的贡献。

由于异或具有前缀和的性质,即为异或和,那么我们的 $s[i] \oplus s[i + 1] \cdots \oplus s[j] = s[j] \oplus s[i - 1] = k$,也就是说,我们的点 $s[j] = s[i - 1] \oplus k$,于是我们对于点 $i$ 来说,加入这个点就会对 $s[i - 1] \oplus k$ 的位置的值产生贡献,使得 $s[i - 1] \oplus s[j] = k$,那么这个题就和 P1494 [国家集训队] 小 Z 的袜子(https://www.cnblogs.com/To-Carpe-Diem/p/19434503) 一样了。


代码

#include<iostream>
#include<cmath>
#include<algorithm>
using namespace std;

const int MAXN = 1e5 + 5;
const int MAXV = (1 << 20) + 5;
int n, m, k, b;
long long sum = 0;
int s[MAXN], a[MAXN];
int cnt[MAXV];
long long ans[MAXN];

struct node{
	int l, r, id;
}q[MAXN];

bool cmp(node x, node y){
	if(x.l / b != y.l / b){
		return x.l < y.l;
	}
	return (x.l / b) % 2 == 1 ? x.r < y.r : x.r > y.r;
}

void add(int x){
	sum += cnt[x ^ k];
	cnt[x] ++;
}

void del(int x){
	cnt[x] --;
	sum -= cnt[x ^ k];
}
int main(){
	ios::sync_with_stdio(0);
	cin.tie(0);

	cin >> n >> m >> k;

	b = sqrt(n);

	for(int i = 1;i <= n;i ++){
		cin >> a[i];
		s[i] = s[i - 1] ^ a[i];
	}

	for(int i = 1;i <= m;i ++){
		int l, r; cin >> l >> r;
		q[i] = {l, r, i};
	}

	sort(q + 1, q + m + 1, cmp);

	int l = 1, r = 0;

	cnt[0] = 1;

	for(int i = 1;i <= m;i ++){
		while(l > q[i].l) add(s[-- l - 1]);
		while(l < q[i].l) del(s[l ++ - 1]);
		while(r < q[i].r) add(s[++ r]);
		while(r > q[i].r) del(s[r --]);
		ans[q[i].id] = sum;
	}

	for(int i = 1;i <= m;i ++){
		cout << ans[i] << '\n';
	}

	return 0;
}


2026-02-04 20:28:29    
我有话要说
暂无人分享评论!