A Simple Problem with Integers
Time Limit: 5000MS | Memory Limit: 131072K |
---|
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
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
相较于HDU -1166 敌兵布阵,HDU -1754 I Hate It多了一个 PushDown()函数
下面讲一下原因
[l,r]对应上图的某个节点
假如执行"C 3 6 3"操作,那么会出现[3]+=3,[4,5]+=6,[6]+=3,这是由Update()函数实现的,
然后执行"Q 2 4"操作,由于[4]在上一步中未被更新,所以答案是"旧的[2]+新的[3]+旧的[4]",但这里应该+“新的[4]”,这是错的,
所以引入了一个add[]数组(又称lazy[]数组),和PushDown()函数。
在第一次"C 3 6 3"操作时,add[ [4,5] ]+=3,相当于子节点[4],[5]的增量暂时由add[ [4,5] ]保管,
在第二次"Q 2 4"操作时,Query()函数寻找[4]节点时递归到了[4,5]节点,所以该节点储存的增量add[ [4,5] ]由PushDown()函数下放给[4],[5]两个子节点,这样答案就是"旧的[2]+新的[3]+新的[4]"
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
#include<queue>
#include<algorithm>
#include<stack>
#include<vector>
using namespace std;
const int maxx=100010;
int a[maxx];
long long sum[maxx*4], add[maxx*4];//要*4,*2会Runtime Error
void Pushup(int rt)
{
sum[rt]=sum[rt*2]+sum[rt*2+1];
}
void Build_tree(int l, int r, int rt)
{
if(l==r)
{
sum[rt]=a[l];
return;
}
int m=(l+r)/2;
Build_tree(l, m, rt*2);
Build_tree(m+1, r, rt*2+1);
Pushup(rt);
}
void PushDown(int rt, int ln, int rn)
{
if(add[rt])//只有该节点的子节点曾经被改变过,且某次递归再次来到该节点
{
add[rt*2]+=add[rt];//子节点暂时保管
add[rt*2+1]+=add[rt];//其子节点的增量
sum[rt*2]+=add[rt]*ln;//ln位rt左子节点管理区间的长度
sum[rt*2+1]+=add[rt]*rn;//rn为rt右子节点管理区间的长度
add[rt]=0;
}
}
void Update(int L, int R, int C, int l, int r, int rt)
{
if(L<=l&&r<=R)
{
sum[rt]+=(r-l+1)*C;
add[rt]+=C;//暂时保管子节点的增量,比如add[ [4,5] ]+=3
return;
}
int m=(r+l)/2;
PushDown(rt, m-l+1, r-m);
if(L<=m)
Update(L, R, C, l, m, rt*2);
if(R>m)
Update(L, R, C, m+1, r, rt*2+1);
Pushup(rt);
}
long long Query(int L, int R, int l, int r, int rt)
{
if(L<=l&&r<=R)
{
return sum[rt];
}
int m=(r+l)/2;
PushDown(rt, m-l+1, r-m);//看看该节点用不用向子节点下放增量
long long ans=0;
if(L<=m)
ans+=Query(L, R, l, m, rt*2);
if(R>m)
ans+=Query(L, R, m+1, r, rt*2+1);
return ans;
}
int main()
{
int n, q;
while(scanf("%d%d", &n, &q)!=EOF)
{
for(int i=1; i<=n; i++)
scanf("%lld", &a[i]);
Build_tree(1, n, 1);
char com;
int a, b, c;
while(q--)
{
scanf(" %c", &com);
if(com=='Q')
{
scanf("%d%d", &a, &b);
long long ans=Query(a, b, 1, n, 1);
printf("%lld\n", ans);
}
else
{
scanf("%d%d%d", &a, &b, &c);
Update(a, b, c, 1, n, 1);
}
}
}
return 0;
}