A Simple Problem with Integers~POJ - 3468

You have N integers, A1A2, ... , 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 A1A2, ... , AN. -1000000000 ≤ Ai ≤ 1000000000.
Each of the next Q lines represents an operation.
"C a b c" means adding c to each of AaAa+1, ... , Ab. -10000 ≤ c ≤ 10000.
"Q a b" means querying the sum of AaAa+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

Hint

The sums may exceed the range of 32-bit integers
 
这题也是线段树的模板题我上一篇写的是单点更新 这一篇为区间更新 。
这题很适合线段树入门。
 
 
 #include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
#define maxn 100005
long long sum[maxn<<],add[maxn<<];
void pushup(int rt) {
sum[rt]=sum[rt<<]+sum[rt<<|];
}
void pushdown(int rt ,int l) {
if (add[rt]) {
add[rt<<]+=add[rt];
add[rt<<|]+=add[rt];
sum[rt<<]+=add[rt]*(l-(l>>));
sum[rt<<|]+=add[rt]*(l>>);
add[rt]=;
}
}
void build(int l,int r,int rt) {
if (l==r) {
scanf("%lld",&sum[rt]);
return ;
}
int m=(l+r)>>;
build(l,m,rt<<);
build(m+,r,rt<<|);
pushup(rt);
}
void updata(int x,int y,int z,int l,int r,int rt) {
if (x<=l && r<=y) {
add[rt]+=z;
sum[rt]+=(long long)z*(r-l+);
return ;
}
pushdown(rt,r-l+);
int m=(l+r)>>;
if (x<=m) updata(x,y,z,l,m,rt<<);
if (y>m) updata(x,y,z,m+,r,rt<<|);
pushup(rt);
}
long long query(int x,int y,int l,int r,int rt) {
long long ans=;
if (x<=l && r<=y ) return sum[rt];
pushdown(rt,r-l+);
int m=(l+r)>>;
if (x<=m) ans+=query(x,y,l,m,rt<<);
if (y>m ) ans+=query(x,y,m+,r,rt<<|);
return ans;
}
int main() {
int n,q;
while(scanf("%d%d",&n,&q)!=EOF) {
build(,n,);
char b[];
int x,y,z;
while(q--) {
scanf("%s",b);
if (b[]=='Q') {
scanf("%d%d",&x,&y);
printf("%lld\n",query(x,y,,n,));
} else {
scanf("%d%d%d",&x,&y,&z);
updata(x,y,z,,n,);
}
}
}
return ;
}
上一篇:Java集合系列:-----------07Map架构


下一篇:SEO人员应该突破的5大思想误区