题目地址:http://poj.org/problem?id=3468
Time Limit: 5000MS | Memory Limit: 131072K | |
Case Time Limit: 2000MS |
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
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
#include <cstring>
#include <iostream>
#include <algorithm>
#include <cstdio>
using namespace std;
long long add[400000];
struct node
{
int l,r;
long long sum;
}tree[400000];
void buildtree(int node,int b,int e)
{
int mid=(b+e)/2;
tree[node].l=b;
tree[node].r=e;
tree[node].sum=0;
if(b==e) return;
if(b<=mid) buildtree(node*2,b,mid);
if(e>mid) buildtree(node*2+1,mid+1,e);
}
void push_down(int node)
{
if(add[node])
{
add[node*2]+=add[node];//标记左右儿子
add[node*2+1]+=add[node];
tree[node*2].sum+=add[node]*(tree[node*2].r-tree[node*2].l+1);//左右儿子的值要改变;
tree[node*2+1].sum+=add[node]*(tree[node*2+1].r-tree[node*2+1].l+1);
add[node]=0;//取消这个标记
}
}
void update(int node,int ql,int qr,long long z)
{
if(tree[node].l>=ql && tree[node].r<=qr)
{
add[node]+=z;
tree[node].sum += z*(tree[node].r-tree[node].l+1);
return;
}
push_down(node);//把这个标记传下去给左右儿子
int mid=(tree[node].l+tree[node].r)/2;
if(ql<=mid) update(node*2,ql,qr,z);
if(qr>mid) update(node*2+1,ql,qr,z);
tree[node].sum=tree[node*2].sum+tree[node*2+1].sum;//把当前更改的值传给父亲
}
long long query(int node,int ql,int qr)
{
long long ans1=0,ans2=0;
if(tree[node].l>=ql && tree[node].r<=qr)
{
return tree[node].sum;
}
push_down(node);//把这个标记传下去给左右儿子
int mid=(tree[node].l+tree[node].r)/2;
if(mid>=ql) ans1 = query(node*2,ql,qr);
if(mid<qr) ans2 =query(node*2+1,ql,qr);
return ans1+ans2;
}
int main()
{
int n,m,x,y;
long long z;
char c;
scanf("%d%d",&n,&m);
buildtree(1,1,n);
for(int i=1;i<=n;++i)
{
cin>>z;
update(1,i,i,z);
}
for(int i=1;i<=m;++i)
{
cin>>c;
if(c == 'Q')
{
scanf("%d%d",&x,&y);
cout<<query(1,x,y)<<endl;
}
else if(c=='C')
{
scanf("%d%d",&x,&y);
cin>>z;
update(1,x,y,z);
}
}
return 0;
}