一维树状数组

click here
1。单点修改,区间查询

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
const int maxn=2e6+10;
typedef long long ll;
ll a[maxn];
int n;
int lowbit(int x)
{
	return x&(-x);
}
void update(int x,ll val)
{
	for(int i=x;i<=n;i+=lowbit(i))
	a[i]+=val;	
}
ll getsum(int x)
{
	ll res=0;
	for(int i=x;i>0;i-=lowbit(i))
	res+=a[i];
	return res;
}
int main()
{
	int m;
	ll p;
	memset(a,0,sizeof a);
	scanf("%d%d",&n,&m);
	for(int i=1;i<=n;i++)
	scanf("%lld",&p),update(i,p);
	while(m--)
	{
		ll t,x,y;
		scanf("%lld%lld%lld",&t,&x,&y);
		if(t==1)
		update(x,y);
		else
		printf("%lld\n",getsum(y)-getsum(x-1));
	}
	return 0;
}

2.区间修改,单点查询
click here

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
const int maxn=2e6+10;
int n,m;
typedef long long ll;
ll a[maxn];
int lowbit(int x)
{
	return x&(-x);
}
void update(int x,ll val)
{
	for(int i=x;i<=n;i+=lowbit(i))
	a[i]+=val;
}
ll getsum(int x)
{
	ll res=0;
	for(int i=x;i>0;i-=lowbit(i))
	res+=a[i];
	return res;
}
int main()
{
	scanf("%d%d",&n,&m);
	ll pl=0;
	for(int i=1;i<=n;i++)
	{
		ll p;
		scanf("%lld",&p);
		update(i,p-pl),pl=p;
	}
	while(m--)
	{
		int x,y;
		ll val;
		int t;
		scanf("%d",&t);
		if(t==1)
		{
			scanf("%d%d%lld",&x,&y,&val);
			update(x,val);
			update(y+1,-val);
		}
		else
		{
			scanf("%d",&x);
			printf("%lld\n",getsum(x));
		}
	}
	return 0;
}

3.区间修改 区间查询
click here

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
const int maxn=2e6+10;
typedef long long ll;
ll a[maxn];
ll n,m;
ll s1[maxn],s2[maxn];
int lowbit(int x)
{
	return x&(-x);
}
void update(int x,ll val)
{
	for(int i=x;i<=n;i+=lowbit(i))
	s1[i]+=val,s2[i]+=(x-1)*val;
}
ll getsum(int x)
{
	ll res=0;
	for(int i=x;i>0;i-=lowbit(i))
	res+=x*s1[i]-s2[i];
	return res;
}

int main()
{
	scanf("%lld%lld",&n,&m);
	ll x,p=0;
	for(int i=1;i<=n;i++)
	scanf("%lld",&x),update(i,x-p),p=x;
	while(m--)
	{
		int t,x,y,val;
		scanf("%d",&t);
		if(t==1)
		{
			scanf("%d%d%d",&x,&y,&val);
			update(x,val);
			update(y+1,-val);
		}
		else
		{
			scanf("%d%d",&x,&y);
			printf("%lld\n",getsum(y)-getsum(x-1));
		}
	}
	return 0;
}

为什么我感觉一维比二维难qwq

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值