xor题解
赛时:40pts
改题:AC
赛时 40pts
首先观察得出
\[b[x][y] = \bigoplus_{i=0}^{x} (C_x^{i} \ mod \ 2) \ a[y+i]\tag{一}
\]
这个比较显然,手玩样例就能得到。
根据提示,
\[C_a^b \bmod 2 = [a \mathbin{\&} b = b]
\]
所以只有 \(i\) 为 \(x\) 子集时,\(C_x^{i} \ mod \ 2 = 1\).
那么只要枚举 \(x\) 子集 \(s\),将 \(a[s + y]\) 加入答案,
就能得到随机数据下可过的代码。
赛时代码:
// xor.cpp
#include<bits/stdc++.h>
using namespace std;
constexpr int N = 1e5 + 7;
int a[N];
int n, q;
int main(){
freopen("xor.in", "r", stdin);
freopen("xor.out", "w", stdout);
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
cin >> n >> q;
for (int i = 0; i < n; i++)
cin >> a[i];
for (int i = 1; i <= q; i++){
int x, y, ans = 0;
cin >> x >> y;
for (int s = x; s >= 0; s = (s - 1) & x){
ans ^= a[s + y];
if (s == 0) break;
}
cout << ans << '\n';
}
}
/*
只要出现 x = (1 << k) - 1
这种情况会被卡。
貌似40pts;
*/
正解 100pts
admin 的题解 40pts 部分比 100pts 部分详细两倍,懒得吐槽了。
在40pts 的部分,我们将 \(b[0]\) 作为起始行开始计算,
admin 说 “那么更一般的,我们可以用第 \(t\) 行来计算……我们可以令 \(t=x\bmod512\)”。
为什么?怎么算?
推一下:
记 $B=512,t=x\bmod B, q=\left \lfloor \frac{x}{B} \right \rfloor $.
显然 \(x - t = qB\).
和推式(一)相同,得到
\[b[x][y] = \bigoplus_{i=0}^{qB} b[t][y+i] \cdot \ [qB \mathbin{\&} \ i = i] \tag{二}
\]
因为 \(512 = 2^9\),
所以 \(qB\) 相当于 \(q\) 左移 \(9\) 位,
那么 \(qB\) 的 \(9\) 个最低位都是 \(0\).
我们记 \(i = jB\),得到
\([qB \mathbin{\&} \ jB = jB]\),
全部右移 \(9\) 位,得到
\([q \mathbin{\&} \ j = j]\).
那么式(二)变为
\[b[x][y] = \bigoplus_{j=0}^{qB\gg9} b[t][y+(j\ll9)] \cdot \ [q \mathbin{\&} \ j = j]
\]
那么只要枚举 \(q\) 子集 \(j\),将 \(b[t][y+(j\ll9)]\) 加入答案,
就能得到AC代码。
#include <bits/stdc++.h>
using namespace std;
constexpr int N = 1e5 + 7, B = 1 << 9;
int n, q;
int a[N], b[B][N];
void init(int T){
for (int i = 1; i < T; i++)
for (int j = 0; j < n - i; j++)
b[i][j] = b[i - 1][j] ^ b[i - 1][j + 1];
}
int main(){
freopen("xor.in", "r", stdin);
freopen("xor.out", "w", stdout);
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
cin >> n >> q;
for (int i = 0; i < n; i++){
cin >> a[i];
b[0][i] = a[i];
}
int maxt = min(B, n);
init(maxt);
while (q--){
int x, y, res = 0;
cin >> x >> y;
int t = x % B, q = x >> 9;
for (int j = q; j >= 0; j = (j - 1) & q){
res ^= b[t][y + (j << 9)];
if (j == 0) break;
}
cout << res << '\n';
}
}

浙公网安备 33010602011771号