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
题意:Q是询问区间和,C是在区间内每个节点加上一个值
思路:这题如果直接更新到叶子节点会超时,所以只要找到一个适合的区间就用一个增量来记录它,当下一次询问时,如果这个范围正好合适询问的范围,就直接是这个节点的sum值加上这个区间长度*lnc,再加到总和上去,若这个节点的范围不适合所要查询的范围,那么就要查询它的子节点,这个时候再把增量传给她的子节点,并且清空父亲节点的增量。
#include
#include
#include
using namespace std;
const int maxn = 100000+10;
int n,m,sum;
struct node
{
int l,r;
__int64 n,sum;//sum为增量
} a[maxn<<2];
void init(int l,int r,int i)
{
a[i].l = l;
a[i].r = r;
a[i].n = 0;
a[i].sum = 0;
if(l!=r)
{
int mid = (l+r)>>1;
init(l,mid,2*i);
init(mid+1,r,2*i+1);
}
}
void insert(int i,int l,int r,__int64 m)
{
a[i].n+=(r-l+1)*m;
if(a[i].l >= l && a[i].r <= r)
a[i].sum+=m;////若此节点所在区段被包含在要插入的区段中,就将插入值存在sum
else
{
int mid = (a[i].l+a[i].r)>>1;
if(r<=mid)
insert(2*i,l,r,m);
else if(l>mid)
insert(2*i+1,l,r,m);
else
{
insert(2*i,l,mid,m);
insert(2*i+1,mid+1,r,m);
}
}
}
__int64 find(int i,int l,int r)
{
if(a[i].l == l && a[i].r == r)
return a[i].n;
else
{
int mid = (a[i].l+a[i].r)>>1;
if(a[i].sum)
{ //若上面if条件不成立,则要询问它的子节点,此时增量要下传,并且要更新其本身的sum;
a[2*i].sum += a[i].sum;
a[2*i].n+=a[i].sum*(a[2*i].r-a[2*i].l+1);
a[2*i+1].sum += a[i].sum;
a[2*i+1].n+=a[i].sum*(a[2*i+1].r-a[2*i+1].l+1);
a[i].sum = 0;
}
if(r<=mid)
return find(2*i,l,r);
else if(l>mid)
return find(2*i+1,l,r);
else
{
return find(2*i,l,mid)+find(2*i+1,mid+1,r);
}
}
}
int main()
{
int i,j,x,y;
__int64 k;
char str[5];
while(~scanf("%d%d",&n,&m))
{
init(1,n,1);
for(i = 1; i<=n; i++)
{
scanf("%I64d",&k);
insert(1,i,i,k);
}
while(m--)
{
scanf("%s%d%d",str,&x,&y);
if(str[0] == 'C')
{
scanf("%I64d",&k);
insert(1,x,y,k);
}
else if(str[0] == 'Q')
printf("%I64d\n", find(1,x,y));
}
}
return 0;
}