(kuangbin带你飞--线段树)A Simple Problem with Integers

原题目:

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

The first line contains two numbers N and Q. 1 ≤ N,Q ≤ 100000.
The second line contains N numbers, the initial values of A1, A2, ... , AN. -1000000000 ≤ Ai ≤ 1000000000.
Each of the next Q lines represents an operation.
"C a b c" means adding c to each of Aa, Aa+1, ... , Ab. -10000 ≤ c ≤ 10000.
"Q a b" means querying the sum of Aa, Aa+1, ... , Ab.

Output

You need to answer all Q commands in order. One answer in a line.

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

 

中文概要:

一行序列,每次操作把一个区间里的每个数都加上一个数,或者查询一个区间的和。

分析:一道模板题吧,就每次叠加就行了,只是注意数据范围int会超

#include<cstdio>
using namespace std;
const int maxn=1e6+10;
typedef long long ll;
struct node
{
	int l,r;
	ll sum,length,lazy;
}a[maxn*4];
int n,m;
void build(int i,int l,int r)
{
	a[i].l=l,a[i].r=r,a[i].sum=a[i].lazy=0;
	a[i].length=(r-l+1);
	if(l==r)
	{
		scanf("%lld",&a[i].sum);
		return ;
	}
	int mid=(l+r)>>1;
	build(i<<1,l,mid);
	build(i<<1|1,mid+1,r);
	a[i].sum=a[i<<1].sum+a[i<<1|1].sum;
}
void pushdown(int i)
{
	if(a[i].lazy)
	{
		a[i<<1].lazy+=a[i].lazy;
		a[i<<1|1].lazy+=a[i].lazy;
		a[i<<1].sum+=a[i<<1].length*a[i].lazy;
		a[i<<1|1].sum+=a[i<<1|1].length*a[i].lazy;
		a[i].lazy=0;
	}
}
ll qu(int i,int l,int r)
{
	if(l<=a[i].l&&a[i].r<=r)
	{
		return a[i].sum;
	}
	pushdown(i);
	int mid=(a[i].l+a[i].r)>>1;
	ll ans=0;
	if(l<=mid) ans+=qu(i<<1,l,r);
	if(r>mid) ans+=qu(i<<1|1,l,r);
	return ans;
}
void up(int i,int l,int r,ll val)
{
	if(l<=a[i].l&&a[i].r<=r)
	{
		a[i].lazy+=val;
		a[i].sum+=a[i].length*val;
		return ;
	}
	pushdown(i);
	int mid=(a[i].l+a[i].r)>>1;
	if(l<=mid) up(i<<1,l,r,val);
	if(r>mid) up(i<<1|1,l,r,val);
	a[i].sum=a[i<<1].sum+a[i<<1|1].sum;
}
int main()
{
	while(~scanf("%d%d",&n,&m))
	{
		build(1,1,n);
		while(m--)
		{
			char s[5];
			scanf("%s",s);
			//printf("a[1].id:%d\n\n",a[1].sum);
			if(s[0]=='Q')
			{
				int x,y;
				scanf("%d%d",&x,&y);
				printf("%lld\n",qu(1,x,y));
			}
			else
			{
				int x,y;
				ll z;
				scanf("%d%d%lld",&x,&y,&z);
				up(1,x,y,z);
			}
		}
	}
}

主要是lazy标记不好理解罢了,其他的还好

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

deebcjrb

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值