数列的异或和—树状数组

样例
样例输入
5 5
1 2 3 4 5
1 1 3
1 3 5
0 3 6
1 1 3
1 3 5
样例输出
0
2
5
7
数据范围与提示
对于100%的数据 0<n<10^5,0<m<10^5,0<ai,y<10^9,1<x,l,r<n
对于40%的数据 0<n<1000,0<m<1000

思路:

求异或和,我们可以联想到位运算中的符号"^"是求异或的符号,题中要求可知为单点修改,区间查询,我们只需要把求和换为求异或就OK啦

看代码:

#include <bits/stdc++.h>
using namespace std;
const int N=100010;
int n,m,k,l,r,a[N],c[N];
int lowbit(const int x){
return x&-x;
}
void add(int x,int key){
while(x<=n){
c[x]=c[x]^key;
x+=lowbit(x);
}
}
int getsum(int x){
int s=0;
while(x){
s=c[x]^s;
x-=lowbit(x);
}
return s;
}
int main(){
cin>>n>>m;
for(int i=1;i<=n;i++){
cin>>a[i];
add(i,a[i]);
}
for(int i=1;i<=m;i++){
cin>>k>>l>>r;
if(k==1){
int ans=getsum(r)^getsum(l-1);
cout<<ans<<endl;
}
else{
add(l,a[l]);
a[l]=r;
add(l,r);
}
}
return 0;
}

如有错误,欢迎大佬们在评论区指正~

#一名爱打篮球的oier#

posted @   __kw  阅读(51)  评论(5编辑  收藏  举报
相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示