【题解提供者】吴立强
解法
思路
注意到对于单次的查询区间 l , r l,r l,r,可以通过前缀异或和拆分为两个新的区间查询: 0 , l − 1 , 0 , r 0, l-1, 0,r 0,l−1,0,r。
对于任意区间 0 , R 0,R 0,R 可以找到最大的 x x x( x ≤ R x \le R x≤R 且 x m o d 4 = 0 x\mod 4 = 0 xmod4=0), 0 , R 0,R 0,R 的异或和等价于 x , R x,R x,R 的异或和。(根据上一题题解中的【拓展】可以求证此结论)
代码展示
cpp
#include <iostream>
using namespace std;
int get(int x) {
if(x < 0) return 0;
int ans = 0;
for(int i = x / 4 * 4; i <= x; i ++) ans ^= i;
return ans;
}
int main() {
int t; cin >> t;
while(t --) {
int l, r; cin >> l >> r;
cout << (get(l - 1) ^ get(r)) << endl;
}
return 0;
}
算法分析
程序时间复杂度为 O ( t ) O(t) O(t)。