来源 POJ3468
题目:
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
Hint
The sums may exceed the range of 32-bit integers.
思路:线段树区间更新模板题,要用到lazy操作。当做记录一下线段树模板
这题数据规模比较大 要用__int64
#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstring>
#define INF 0x3f3f3f3f
#define mod 1000000007
#define pi acos(-1)
using namespace std;
__int64 add[100010*4],sum[100010*4],ans;
int n;
void build(int t,int l,int r)
{
if(l==r)
{
scanf("%I64d",&sum[t]);
}
else
{
build(t*2,l,(l+r)/2);
build(t*2+1,(l+r)/2+1,r);
sum[t]=sum[t*2]+sum[t*2+1];
}
}
void pushDown(int t,int len)
{
add[t*2]+=add[t];
add[t*2+1]+=add[t];
sum[t*2]+=(len-(len/2))*add[t];
sum[t*2+1]+=(len/2)*add[t];
add[t]=0;
}
void update(int t,int l,int r,int L,int R,int z)
{
if(L<=l && r<=R)
{
add[t]+=z;
sum[t]+=(r-l+1)*z;
}
else
{
if(add[t])
pushDown(t,r-l+1);
if(L<=(l+r)/2)
update(t*2,l,(l+r)/2,L,R,z);
if(R>(l+r)/2)
update(t*2+1,(l+r)/2+1,r,L,R,z);
sum[t]=sum[t*2]+sum[t*2+1];
}
}
__int64 search(int t,int l,int r,int L,int R)
{
if(L<=l && r<=R)
{
return sum[t];
}
else
{
if (add[t])
pushDown(t,r-l+1);
__int64 tmp=0;
if(L<=(l+r)/2)
tmp+=search(t*2,l,(l+r)/2,L,R);
if(R>(l+r)/2)
tmp+=search(t*2+1,(l+r)/2+1,r,L,R);
return tmp;
}
}
int main()
{
int q,A,B,C;
char s;
cin>>n>>q;
build(1,1,n);
while (q--)
{
scanf(" %c",&s);
if (s=='Q')
{
scanf("%d%d",&A,&B);
ans=search(1,1,n,A,B);
printf("%I64d\n",ans);
}
else
{
scanf("%d%d%d",&A,&B,&C);
update(1,1,n,A,B,C);
}
}
return 0;
}