A Simple Problem with Integers(模板)

传送门POJ - 3468

描述

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.

输入

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.

输出

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

样例

  • 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
  • Output
    4
    55
    9
    15

思路

  • 题意:给1到n个数,输入Q,则询问[x,y]区间和;输入C,则在区间[x,y]加上z;
  • 线段树,区间修改区间查询

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include<stdio.h>
#include<cstring>
#define LL long long
#define INIT(a,b) memset(a,b,sizeof(a))
struct Tree{
LL num,k,l,r;
}tree[400007];
void build(LL l,LL r,LL d){ //建树
tree[d]=(Tree){0,0,l,r};
if(l==r){
scanf("%lld",&tree[d].num );
return ;
}
LL mid=(l+r)/2;
build(l,mid,d<<1);
build(mid+1,r,d<<1|1);
tree[d].num=tree[d<<1].num+tree[d<<1|1].num;
}
void down(LL d){ //标记下传并更新子节点的值
tree[d<<1].k+=tree[d].k;
tree[d<<1|1].k+=tree[d].k;
tree[d<<1].num+=tree[d].k*(tree[d<<1].r-tree[d<<1].l+1);
tree[d<<1|1].num+=tree[d].k*(tree[d<<1|1].r-tree[d<<1|1].l+1);
tree[d].k=0;
}
void add(LL l,LL r,LL a,LL d){ //区间更新
if(tree[d].l==l&&tree[d].r==r){
tree[d].num+=a*(tree[d].r-tree[d].l+1);
tree[d].k+=a;
return;
}
if(tree[d].k)down(d);
LL mid=(tree[d].l+tree[d].r)/2;
if(mid>=r) add(l,r,a,d<<1);
else if(mid<l) add(l,r,a,d<<1|1);
else {
add(l,mid,a,d<<1);
add(mid+1,r,a,d<<1|1);
}
tree[d].num=tree[d<<1].num+tree[d<<1|1].num;
}
LL find(LL l,LL r,LL d){ //区间查找
if(tree[d].l==l&&tree[d].r==r)
return tree[d].num;
if(tree[d].k)down(d);
LL mid=(tree[d].l+tree[d].r)/2;
if(mid>=r) return find(l,r,d<<1);
else if(mid<l) return find(l,r,d<<1|1);
else return find(l,mid,d<<1)+find(mid+1,r,d<<1|1);
}
int main(){
LL n,q,tem;
scanf("%lld %lld",&n,&q);
build(1,n,1);
char s[5];LL x,y,z;
while(q--){
scanf("%s",&s);
if(s[0]=='Q'){
scanf("%lld %lld",&x,&y);
printf("%lld\n",find(x,y,1));
}
else{
scanf("%lld %lld %lld",&x,&y,&z);
add(x,y,z,1);
}
}
return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值