树状数组板子

两种操作时间复杂度O(logn),空间复杂度O(n)

build方法

const int maxn=5e5+5;	int n,m;
int s[maxn];
void build(){
	rep(i,1,n){
		int x;cin>>x;change(i,x);
	}
}

lowbit方法(求x的最低位二次幂)(-x的二进制表示为 x二进制取反+1)

int lowbit(int x){
	return x&-x;
}

change方法(树状数组下标为x的值加上k)(向后加

void change(int x,int k){
	while(x<=n){
		s[x]+=k;
		x+=lowbit(x);
	}
}

query方法(查询1~x范围的元素和)(向前查

int query(int x){
	int t=0;
	while(x){
		t+=s[x];
		x-=lowbit(x);
	}
	return t;
}
posted @ 2025-02-16 09:56  Marinaco  阅读(10)  评论(0)    收藏  举报
//雪花飘落效果