其他分享
首页 > 其他分享> > AT4142 [ARC098B] Xor Sum 2 题解

AT4142 [ARC098B] Xor Sum 2 题解

作者:互联网

本题首先需要注意到几个性质:

  1. \(x \oplus y \leq x+y\) 。
  2. \(x \oplus y = z\) 等价于 \(x \oplus z = y\) 。

搞清楚这两点,题目就好做了。

首先,对于满足要求的连续区间 \([l,r]\) ,如果加入数 \(a_{r+1}\) 之后不平衡了,那么我们直接弹出 \(a_l\) 即可,根据性质 2 以及众所周知的加减法逆运算更新即可。

因此根据上述描述,可以采用 尺取法 解决本题。

着重讲一讲更新答案:

假设两个指针为 \(pos1,pos2\) ,答案为 \(ans\) ,那么我们令 \(ans += pos2 - pos1 + 1\) 。为什么只需要加入区间长度?是因为之前的数对我们已经在之前的区间中统计过了,因此这里不需要重新统计,只需要计算 \(pos2\) 对区间 \([pos1,pos2-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;
}

标签:AT4142,ch,Xor,int,题解,long,ans,pos2,pos1
来源: https://www.cnblogs.com/Plozia/p/16113983.html