跳到正文

个人记录

7.18 树状数组

wmml约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年7月19日
收录
2025年12月12日
更新
2026年11月13日
篇幅
约 3 分钟

版本

  1. v1当前

树状数组:

lowbit:获取x的二进制表示中最低位的1所对应的值

modify:修改原数组a[x]的(增加 v)并更新树状数组中所有受影响的位置

query:查询前缀和

c[x]长度=lowbit(x)

每层lowbit长度相等

c[x]存储的是以x结尾,长度为lowbit(x)的区间答案

T1

C++
#include<bits/stdc++.h> 
using namespace std;
long long n,q;
long long a[1000010],c[1000010];
int lowbit(int x){
	return (x&(-x));
} 
long long query(int x){
	long long sum=0;
	while(x){
		sum+=c[x];
		x-=lowbit(x);
	}
	return sum;
}
void modify(int x,int v){
	while(x<=n){
		c[x]+=v;
		x+=lowbit(x);
	}
	return;
}
int main(){
	scanf("%lld%lld",&n,&q);
	for(int i=1;i<=n;i++){
		scanf("%lld",&a[i]);
		modify(i,a[i]);
	}
	while(q--){
		long long x,y,z;
		scanf("%lld%lld%lld",&x,&y,&z);
		if(x==1){
			modify(y,z);
		}
		else printf("%lld\n",query(z)-query(y-1));
	}
	return 0;
}

T2

C++
#include<bits/stdc++.h> 
using namespace std;
long long n,q;
long long a[1000010],c[1000010];
int lowbit(int x){
	return (x&(-x));
} 
long long query(int x){
	long long sum=0;
	while(x){
		sum^=c[x];
		x-=lowbit(x);
	}
	return sum;
}
void modify(int x,int v){
	while(x<=n){
		c[x]^=v;
		x+=lowbit(x);
	}
	return;
}
int main(){
	scanf("%lld%lld",&n,&q);
	while(q--){
		long long x,y,z;
		scanf("%lld%lld",&x,&y);
		if(x==1){
			scanf("%lld",&z);
			modify(y,1);
			modify(z+1,1);
		}
		else printf("%lld\n",query(y)%2);
	}
	return 0;
}
原文