树状数组成段更新模板

这个成段的编写复杂度很低,不需要加大空间复杂度,便于处理成段加,询问每个位置的值的操作:

#include <bits/stdc++.h>
using namespace std ;
typedef long long ll ;
typedef long double ld ;
typedef unsigned long long ull ;
#ifdef _WIN32
#define LLD "%I64d"
#else
#define LLD "%lld"
#endif
#define pi (acos(-1.0))
#define F first
#define S second
#define lson (o<<1),l,mid
#define rson (o<<1|1),mid+1,r
#define MP make_pair
const double eps = 1e-9 ;
const int inf = 0x3f3f3f3f ;
const ll INF = (ll)4e18 ;

const int M = (int)1e5+10 ;
struct BIT {
	ll u[M] ;
	int n ;
	void clr(int _n) { 
		n = _n ;
		memset (u,0,sizeof(int)*(n+1)) ;
	}

	void add (int x , ll v) {
		for (; x<=n ; x += x&-x) u[x] += v ;
	}
	void add (int l , int r , ll v) {
		add(l,v) ; add(r+1,-v) ;
	}
	ll get (int x , ll ret=0) {
		for (; x>0 ; x -= x&-x) ret += u[x] ;
		return ret ;
	}
}bit ;

int main () {
	int a[20] = {0,3,7,4,8,9,11,5,4,9,1} ;
	for (int i=1 ; i<=10 ; i++) printf ("%-4d" , a[i]) ; puts ("");

	bit.clr (10) ;
	for (int i=10 ; i>0 ; i--) {
		a[i] = a[i]-a[i-1] ;
		bit.add(i,i,a[i]) ;
	}
	for (int i=1 ; i<=10 ; i++) printf ("%-4d",a[i]) ; puts ("");
	for (int i=1 ; i<=10 ; i++) printf ("%-4d" , bit.u[i]) ; puts ("") ;
	int Q ;
	scanf ("%d" , &Q) ;
	while (Q --) {
		int x ;
		scanf ("%d" , &x) ;
		printf ("%d\n" , bit.get(x) ) ;
	}
	return 0 ;
}

  

posted @ 2016-04-27 14:27  92度的苍蓝  阅读(340)  评论(0编辑  收藏  举报
http://images.cnblogs.com/cnblogs_com/Running-Time/724426/o_b74124f376fc157f352acc88.jpg