模板---树状数组(各种变形)

 原版::

const int N = 100100;
int sz[N];
int lowbit(itn x)
{
	return x&(-x);
}
//更新节点 
void update(int x,int d)
{
	while(x < N)
	{
		sz[x] = sz[x]+d;
		x = x+lowbit(x);
	}
}
//区间和 [0,x]
int getsum(int x)
{
	int res = 0;
	while(x > 0)
	{
		res = res+sz[x];
		x = x-lowbit(x) ;
	}
	return res;
}

区间修改,单点查询::

//定义为 a[i] = c1[i]-c1[i-1]
//则 a[i] = c1[0]+ca[i]+...+c1[i]
const int N = 100100;
int a[N],c1[N]; 
int lowbit(int x)
{
	return x&(-x);
}
void update(int x,int d)
{
	while(x < N)
	{
		c1[x] = c1[x]+d;
		x = x+lowbit(x);
	}
}
int getsum(int x)
{
	int res = 0;
	while(x > 0)
	{
		res = res+c1[x];
		x = x-lowbit(x) ;
	}
	return res;
}
/*
*输入处理
*	update(i,a[i]-a[i-1]);
*
*修改区间 [l,r] + ad 
*	update(l,ad);
*	update(r+1,-ad);
*
*查询位置 x 的值
*	x = getsum(x);
*
*/

区间修改,区间查询::

//定义 c1[i]  = a[i]-a[i-1];
//则   a[i] = c1[0]+c1[1]+...+c1[i]
//由 sum(1,k) = c1[1]+
//              (c1[1]+c1[2])+
//              (c1[1]+c1[2]+c1[3])+
//              ...+
//              (c1[1]+c1[2]+c1[3]+...+c1[k])
//可知sum(1,k) = k*(c1[1]+...+c1[k])-
//               (0*c1[1] + 1*c1[2] + 2*c1[3] +...+ (k-1)*c1[k])
//则定义c2[i] = (i-1)*c1[i];const int N = 100100;
int a[N],c1[N],c2[N]; 
int lowbit(itn x)
{
	return x&(-x);
}
void update(int *q,int x,int d)
{
	while(x < N)
	{
		c1[x] = c1[x]+d;
		x = x+lowbit(x);
	}
}
int getsum(int *q,int x)
{
	int res = 0;
	while(x > 0)
	{
		res = res+c1[x];
		x = x-lowbit(x) ;
	}
	return res;
}

int sum(int x)
{
	int ans1,ans2;
	ans1 = x*getsum(c1,x);
	ans2 = getsum(c2,x);
	return ans1 - ans2;
}
int query(int l,int r)
{
	int ans1,ans2;
	ans1 = sum(y);
	ans2 = sum(x-1);
	return ans1 - ans2;
}
/* 
*输入处理
*	update(c1,i,a[i]-a[i-1]);
*	update(c2,i,(i-1)*(a[i]-a[i-1]));
*
*修改区间 [l,r] + ad
*	update(c1,l,ad);
*	update(c1,r+1,-ad);
*	update(c2,l,(l-1)*ad);
*	update(c2,r+1,-r*ad);
*
*查询区间和 [l,r] 
*	query(l,r);
*/

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值