3212: Pku3468 A Simple Problem with Integers
Time Limit: 1 Sec Memory Limit: 128 MBSubmit: 1954 Solved: 857
[ Submit][ Status][ Discuss]
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
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
55
9
15
HINT
The sums may exceed the range of 32-bit integers.
线段树裸题
注意区间修改区间查询什么的
是
int mid=(e[ro].l+e[ro].r)>>1;
if(l<=mid) ans+=query(ro<<1,l,r);
if(r>mid) ans+=query(ro<<1|1,l,r);
而不是
int mid=(e[ro].l+e[ro].r)>>1;
if(l<=mid) ans+=query(ro<<1,l,mid);
if(r>mid) ans+=query(ro<<1|1,mid+1,r);
好久没敲板子
这个都忘了
#include<cstdio>
#include<cstring>
const int N=100000;
struct node
{
int l,r;
long long sum,lazy;
}e[N*4];
void pushup(int ro)
{
e[ro].sum=e[ro<<1].sum+e[ro<<1^1].sum;
}
void build(int ro,int l,int r)
{
e[ro].l=l,e[ro].r=r;
if(l==r)
{
scanf("%lld",&e[ro].sum);
return ;
}
int mid=(l+r)>>1;
build(ro<<1,l,mid);build(ro<<1^1,mid+1,r);
pushup(ro);
}
void pushdown(int ro)
{
if(e[ro].lazy)
{
int p=ro<<1,q=p|1;
e[p].sum+=(e[p].r-e[p].l+1)*e[ro].lazy;
e[q].sum+=(e[q].r-e[q].l+1)*e[ro].lazy;
e[p].lazy+=e[ro].lazy;
e[q].lazy+=e[ro].lazy;
e[ro].lazy=0;
}
}
void add(int ro,int l,int r,int k)
{
if(l<=e[ro].l&&e[ro].r<=r)
{
e[ro].sum+=(e[ro].r-e[ro].l+1)*k;
e[ro].lazy+=k;
return ;
}
pushdown(ro);
int mid=(e[ro].l+e[ro].r)>>1;
if(l<=mid) add(ro<<1,l,r,k);
if(r>mid) add(ro<<1|1,l,r,k);
pushup(ro);
}
long long query(int ro,int l,int r)
{
// printf("std::%d %d\n",l,r);
if(l<=e[ro].l&&e[ro].r<=r)
{
// printf("std::%d %d %d %d\n",e[ro].l,e[ro].r,l,r);
return e[ro].sum;
}
pushdown(ro);
long long ans=0;
int mid=(e[ro].l+e[ro].r)>>1;
if(l<=mid) ans+=query(ro<<1,l,mid);
if(r>mid) ans+=query(ro<<1|1,mid+1,r);
return ans;
}
int main()
{
int n,q;
scanf("%d %d",&n,&q);
build(1,1,n);
for(int i=1;i<=q;i++)
{
char a[5];int u,v,m;
scanf("%s",a);
if(a[0]=='Q') scanf("%d %d",&u,&v),printf("%lld\n",query(1,u,v));
else scanf("%d %d %d",&u,&v,&m),add(1,u,v,m);
}
return 0;
}