树状数组关于区间修改区间求和的问题

本文介绍了一种基础的数据结构算法——区间修改与区间求和问题的实现方法,通过使用差分数组和树状数组来高效地处理一系列数值的更新与查询操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Total Submission(s) : 77   Accepted Submission(s) : 19
Problem Description

You have N integers, A1,A2, ... ,AN. You need to deal with two kinds of operations. One type of operation is to add some given number to each number in a given interval. The other is to ask for the sum of numbers in a given interval.

 

Input
<p>The first line contains two numbers <i>N</i> and <i>Q</i>. 1 ≤ <i>N</i>,<i>Q</i> ≤ 100000.<br>The second line contains <i>N</i> numbers, the initial values of <i>A</i><sub>1</sub>, <i>A</i><sub>2</sub>, ... , <i>A<sub>N</sub></i>. -1000000000 ≤ <i>A<sub>i</sub></i> ≤ 1000000000.<br>Each of the next <i>Q</i> lines represents an operation.<br>"C <i>a</i> <i>b</i> <i>c</i>" means adding <i>c</i> to each of <i>A<sub>a</sub></i>, <i>A<sub>a</sub></i><sub>+1</sub>, ... , <i>A<sub>b</sub></i>. -10000 ≤ <i>c</i> ≤ 10000.<br>"Q <i>a</i> <i>b</i>" means querying the sum of <i>A<sub>a</sub></i>, <i>A<sub>a</sub></i><sub>+1</sub>, ... , <i>A<sub>b</sub></i>.</p>
 

Output
<p>You need to answer all <i>Q</i> commands in order. One answer in a line.</p>
 

Sample Input
10 5 1 2 3 4 5 6 7 8 9 10 Q 4 4 Q 1 10 Q 2 4 C 3 6 3 Q 2 4
 

Sample Output
4 55 9 15
题意:
就是给你N个数M个操作,然后输出每一个查询区间的和。 
这是最基础的区间修改区间求和的实现问题。
#if 0
#include<iostream>
#include<cstring>
#include<stdio.h>

using namespace std;
const int MAXN=100000+50;
typedef long long ll;
ll  b[MAXN],c[MAXN];
ll  a[MAXN]; 

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

void add_B(ll  *a,ll  x,ll  v)
{
	for( ; x>0; x-=lowbit(x))
		a[x]+=v;
}
ll sum_B(ll  *a,ll  x)
{
	ll  s=0;
	for(; x<MAXN; x+=lowbit(x))
	{
		s+=a[x];
	}
	
	return s;
}

void add_C(ll  *a,ll  x,ll v)
{
	for( ; x<MAXN; x+=lowbit(x))
	{
		a[x]+=v;
	}
	
}
ll sum_C(ll *a, ll x)
{
	ll s=0;
	for( ; x>0; x-=lowbit(x))
	{
		s+=a[x];
	}
	return s;
}

void add(ll x,ll v)
{
	add_B(b,x-1,v);
	add_C(c,x,v*x);
}
void go_add(ll a,ll b,ll v)
{
	add(b,v);
	add(a-1,-v); //
}

ll sum(ll x)
{
	return sum_C(c,x)+sum_B(b,x)*x;
}
ll go_sum(ll a,ll b)
{
	return sum(b)-sum(a-1);
}

int main()
{


	ll n,t;
	char ssc;

	scanf("%lld%lld",&n,&t);
	
	memset(a,0,sizeof(a));
	memset(b,0,sizeof(b));
	memset(c,0,sizeof(c));
	
	for(int i=3; i<=n+2; i++)
	{
		ll x;
		scanf("%lld",&x);
		go_add(i,i,x);
	}
	

	while(t--)
	{
		
		cin>>ssc;
		if(ssc=='Q')
		{
			ll ai,bi;
			
			scanf("%lld%lld",&ai,&bi);
			ai+=2;
			bi+=2;
	
			
			printf("%lld\n",go_sum(ai,bi));	
		}
		else if(ssc=='C')
		{
			ll ai,bi;
			ll v;
			scanf("%lld%lld%lld",&ai,&bi,&v);
			
			ai+=2;
			bi+=2;
			go_add(ai,bi,v);
		}

	}


}
#endif


























评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值