AT4142 [ARC098B] Xor Sum 2 題解
阿新 • • 發佈:2022-04-13
本題首先需要注意到幾個性質:
- \(x \oplus y \leq x+y\) 。
- \(x \oplus y = z\) 等價於 \(x \oplus z = y\) 。
搞清楚這兩點,題目就好做了。
首先,對於滿足要求的連續區間 \([l,r]\) ,如果加入數 \(a_{r+1}\) 之後不平衡了,那麼我們直接彈出 \(a_l\) 即可,根據性質 2 以及眾所周知的加減法逆運算更新即可。
因此根據上述描述,可以採用 尺取法 解決本題。
著重講一講更新答案:
假設兩個指標為 \(pos1,pos2\) ,答案為 \(ans\) ,那麼我們令 \(ans += pos2 - pos1 + 1\)
Q:如果這麼說,難道答案不是 \(pos2-pos1\) 嗎?為什麼還要再加 1?
A:這是因為還有自己異或自己的答案。
友善的作者在此貼心提醒您:
道路千萬條,long long 第一條。
結果存 int ,爆零兩行淚。
程式碼:
#include <bits/stdc++.h> using namespace std; const int MAXN = 2e5 + 10; int n, a[MAXN]; typedef long long LL; LL ans; int read() { int sum = 0, fh = 1; char ch = getchar(); while (ch < '0' || ch > '9') {if (ch == '-') fh = -1; ch = getchar();} while (ch >= '0' && ch <= '9') {sum = (sum << 3) + (sum << 1) + (ch ^ 48); ch = getchar();} return sum * fh; } int main() { n = read(); for (int i = 1; i <= n; ++i) a[i] = read(); int pos1 = 1, pos2 = 0, s1 = 0, s2 = 0; while (pos1 <= n && pos2 <= n) { while(pos2 + 1 <= n && (s1 + a[pos2 + 1]) == (s2 ^ a[pos2 + 1])) {pos2++; s1 += a[pos2]; s2 ^= a[pos2];} ans += (LL)pos2 - pos1 + 1; s1 -= a[pos1]; s2 ^= a[pos1]; pos1++; } printf ("%lld\n", ans); return 0; }