洛谷树状数组1、2

传送门

树状数组1

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#define re register
using namespace std;

inline long long read() {
	char ch = getchar();
	long long f = 1 , x = 0;
	while(ch > '9' || ch < '0') {if(ch == '-') f = -1 ;ch = getchar();}
	while(ch >= '0' && ch <= '9') {x = (x << 1) + ( x << 3) + ch - '0';ch = getchar();}
	return x * f;
}

long long n,a,m,flag,x,y;
long long c[500005];

inline long long lowbit(long long x){return x & (-x) ;}

inline void add(long long x , long long y){
	while(x <= n) {
		c[x] += y ;
		x += lowbit(x);
	}
}

inline long long sum(long long x){
	long long ans = 0;	 
	while(x) {
		ans += c[x] ;
		x -= lowbit(x);
	}
	return ans;
}

int main(){
	n = read(); m = read();
	for(int i = 1 ; i <= n ; ++i) {
		a = read();
		add(i , a) ;
	}
	for(re int i = 1 ; i <= m ; ++i) {
		flag = read(); 
		if(flag == 1) {
			x = read(); y = read();
			add(x , y);
		}
		if(flag == 2) {
			x = read(); y = read();
			printf("%lld
" , sum(y) - sum(x - 1));
		}
	}
	return 0;
}

传送门

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#define re register
using namespace std;

inline long long read() {
	char ch = getchar();
	long long f = 1 , x = 0;
	while(ch > '9' || ch < '0') {if(ch == '-') f = -1 ;ch = getchar();}
	while(ch >= '0' && ch <= '9') {x = (x << 1) + ( x << 3) + ch - '0';ch = getchar();}
	return x * f;
}

long long n,a,m,flag,x,y,w,last;
long long c[500005];

inline long long lowbit(long long x){return x & (-x) ;}

inline void add(long long x , long long y){
	while(x <= n) {
		c[x] += y ;
		x += lowbit(x);
	}
}

inline long long query(long long x){
	long long ans = 0;
	while(x) {
		ans += c[x];
		x -= lowbit(x);
	}
	return ans;
}

int main(){
	n = read(); m = read();
	for(re int i = 1 ; i <= n ; ++i) {
		a = read();
		add(i , a - last);
		last = a ;
	}
	for(re int i = 1 ; i <= m ; ++i) {
		flag = read();
		if(flag == 1) {
			x = read(); y = read(); w = read();
			add(x , w);
			add(y + 1 , -w);
		}
		else {
			x = read();
			printf("%lld
",query(x));
		}
	}
	return 0;
}
原文地址:https://www.cnblogs.com/Stephen-F/p/9933086.html