时间限制: 1 Sec 内存限制: 128 MB
题目描述
There is an integer sequence A of length N.
Find the number of the pairs of integers l and r (1≤l≤r≤N) that satisfy the following condition:
Al xor Al+1 xor … xor Ar=Al + Al+1 + … + Ar
Here, xor denotes the bitwise exclusive OR.
Definition of XOR
Constraints
1≤N≤2×105
0≤Ai<220
All values in input are integers.
输入
Input is given from Standard Input in the following format:
N
A1 A2 … AN
输出
Print the number of the pairs of integers l and r (1≤l≤r≤N) that satisfy the condition.
样例输入 Copy
4 2 5 4 6
样例输出 Copy
5
提示
(l,r)=(1,1),(2,2),(3,3),(4,4) clearly satisfy the condition. (l,r)=(1,2) also satisfies the condition, since A1 xor A2=A1 + A2=7. There are no other pairs that satisfy the condition, so the answer is 5.
异或性质:a^b^a=b,a^b^c^c^b=a......
时间复杂度的处理
//爆复杂度的
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int n;
ll a[200005],sum[200005],xxor[200005];
int main()
{
scanf("%lld",&n);
for(ll i=1; i<=n; i++)
{
scanf("%lld",&a[i]);
sum[i]=sum[i-1]+a[i];
xxor[i]=xxor[i-1]^a[i];
}
ll ans=n;
int l=1,r=0;
while(l<=n&&r<=n)
{
while(l>r)
r++;
while( ((sum[r]-sum[l-1])==(xxor[r]^xxor[l-1])) &&l<=n&&r<=n)
{
if(r>l)
{
ans++;
}
r++;
}
l++;
r=l+1;
}
printf("%lld\n",ans);
return 0;
}
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int n;
ll a[200005];
ll sum,xxor;
deque<ll>dq;
int main()
{
scanf("%lld",&n);
for(ll i=1; i<=n; i++)
{
scanf("%lld",&a[i]);
}
ll ans=0;
for(int i=1;i<=n;i++)
{
dq.push_back(a[i]);
sum+=a[i];
xxor^=a[i];
while(sum!=xxor)
{
if(dq.empty()) break;
ll temp=dq.front();
dq.pop_front();
sum-=temp;
xxor^=temp;
}
ans+=dq.size();
}
printf("%lld\n",ans);
return 0;
}