A Simple Problem with Integers
Time Limit: 5000MS Memory Limit: 131072K
Total Submissions: 83559 Accepted: 25862
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 <iostream>
#include <math.h>
#include <string.h>
#include <algorithm>
#include <stdlib.h>
using namespace std;
#define MAX 100000
long long int segTree[MAX*4+5];
long long int add[MAX*4+5];
int n,q;
char a;
int x,y,z;
void PushUp(int node)
{
segTree[node]=segTree[node<<1]+segTree[node<<1|1];
}
void PushDown(int node,int m)
{
if(add[node]!=0)
{
add[node<<1]+=add[node];
add[node<<1|1]+=add[node];
segTree[node<<1]+=add[node]*(m-(m>>1));
segTree[node<<1|1]+=add[node]*(m>>1);
add[node]=0;
}
}
void build(int node,int begin,int end)
{
add[node]=0;
if(begin==end)
{
scanf("%lld",&segTree[node]);
return;
}
int m=(begin+end)>>1;
build(node<<1,begin,m);
build(node<<1|1,m+1,end);
PushUp(node);
}
void Update(int node,int begin,int end,int left,int right,int num)
{
if(left<=begin&&end<=right)
{
add[node]+=num;
segTree[node]+=num*(end-begin+1);
return;
}
PushDown(node,end-begin+1);
int m=(begin+end)>>1;
if(left<=m)
Update(node<<1,begin,m,left,right,num);
if(right>m)
Update(node<<1|1,m+1,end,left,right,num);
PushUp(node);
}
long long int Query(int node,int begin,int end,int left,int right)
{
if(left<=begin&&end<=right)
return segTree[node];
PushDown(node,end-begin+1);
int m=(begin+end)>>1;
long long int ret=0;
if(left<=m)
ret+=Query(node<<1,begin,m,left,right);
if(right>m)
ret+=Query(node<<1|1,m+1,end,left,right);
return ret;
}
int main()
{
while(scanf("%d%d",&n,&q)!=EOF)
{
build(1,1,n);
long long int ans;
for(int i=0;i<q;i++)
{
ans=0;
getchar();
scanf("%c",&a);
if(a=='Q')
{
scanf("%d%d",&x,&y);
ans=Query(1,1,n,x,y);
printf("%lld\n",ans);
}
else
{
scanf("%d%d%d",&x,&y,&z);
Update(1,1,n,x,y,z);
}
}
}
return 0;
}