ACM: A Simple Problem with Integers 解题报告-线段树

时间:2024-04-02 11:04:44
 A Simple Problem with Integers
Time Limit:5000MS Memory Limit:131072KB 64bit IO Format:%lld & %llu Description
给出了一个序列,你需要处理如下两种询问。 "C a b c"表示给[a, b]区间中的值全部增加c (-10000 ≤ c ≤ 10000)。 "Q a b" 询问[a, b]区间中所有值的和。 Input
第一行包含两个整数N, Q。1 ≤ N,Q ≤ 100000. 第二行包含n个整数,表示初始的序列A (-1000000000 ≤ Ai ≤ 1000000000)。 接下来Q行询问,格式如题目描述。 Output
对于每一个Q开头的询问,你需要输出相应的答案,每个答案一行。 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

  //用到懒惰标记法。

//Query查询求和,UpData更新数据。

//AC代码:

 #include"iostream"
#include"algorithm"
#include"cstdio"
#include"cstring"
#include"cmath"
using namespace std;
#define MX 1000000 + 10
#define INF 0
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1 long long sum[MX<<]; //数据很大可能会爆int,用long long
long long lazy[MX<<]; void PushUp(int rt) {
sum[rt]=sum[rt<<]+sum[rt<<|];
} void PushDown(int rt,int m) {
if(lazy[rt]) { //如果存在懒惰标记就把标记下移;
lazy[rt<<] +=lazy[rt];
lazy[rt<<|]+=lazy[rt];
sum[rt<<] +=lazy[rt]*(m-(m>>));
sum[rt<<|] +=lazy[rt]*(m>>);
lazy[rt]=INF;
}
} void Build(int l,int r, int rt) {
lazy[rt]=INF; //清空懒惰标记
if(r==l) {
scanf("%I64d",&sum[rt]); //输入每个叶节点的值
return ;
}
int m=(r+l)>>;
Build(lson);
Build(rson);
PushUp(rt);
} void UpData(int L,int R,int c,int l,int r,int rt) {
if (L<=l&&r<=R) {
lazy[rt]+=c; //输要改变的值,记录懒惰标记 。
sum[rt]+=(r-l+)*c; //中间N个数都要进行相同的加减。
return ;
}
PushDown(rt,r-l+); //下移懒惰标记
int m=(r+l)>>;
if(L<=m) UpData(L,R,c,lson);
if(R> m) UpData(L,R,c,rson);
PushUp(rt);
} long long Query(int L,int R,int l,int r,int rt) {
if(L<=l&&r<=R) return sum[rt];
PushDown(rt,r-l+);
//【这步不能少,如果区间没有全部包括,要保证每一个标记都放到目标子节点】
int m=(r+l)>>;
long long ret=;
if(L<=m) ret+=Query(L,R,lson);
if(R> m) ret+=Query(L,R,rson);
return ret;
} int main() {
int n,q;
while(~scanf("%d%d",&n,&q)) {
Build(,n,);
char s[];
int a,b,c;
for(int i=; i<q; i++) {
scanf("%s",s);
if(s[]=='Q') {
scanf("%d%d",&a,&b);
printf("%I64d\n",Query(a,b,,n,));
} else if(s[]=='C') {
scanf("%d%d%d",&a,&b,&c);
UpData(a,b,c,,n,);
}
}
}
return ;
}