题目描述
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.
输入
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.
输出
You need to answer all Q commands in order. One answer in a line.
样例输入
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
样例输出
4 55 9 15
提示
The sums may exceed the range of 32-bit integers.
思路
基础线段树区间更新维护区间和。 注意: 因为数据关系,所以sum数组要用long long,而且,query函数返回值也要用long long,query函数里定义的ans变量也要用long long 。 别问我怎么知道的。 先面给出我的代码,其实可以写一个结构体,不过这样写也无所谓对吧。
代码
#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <math.h>
#include <cstring>
#include <queue>
#include <map>
#include <vector>
#include <string>
#define mem(a) memset(a,0,sizeof(a))
#define mem2(a) memset(a,-1,sizeof(a))
#define mod 1000000007
#define mx 100005
using namespace std;
long long a[mx],sum[mx<<
2],add[mx<<
2];
int n,l;
void pushup (
int x)
{
sum[x]=sum[x<<
1]+sum[x<<
1|
1];
}
void build (
int l,
int r,
int x)
{
if(l==r)
{
sum[x]=a[l];
return;
}
int mid = (l+r)/
2;
build(l,mid,x<<
1);
build(mid+
1,r,x<<
1|
1);
pushup(x);
}
void pushdown (
int x,
int lx,
int rx)
{
if(add[x])
{
add[x<<
1]+=add[x];
add[x<<
1|
1]+=add[x];
sum[x<<
1]+=add[x]*lx;
sum[x<<
1|
1]+=add[x]*rx;
add[x]=
0;
}
}
void update (
int L,
int R,
int C,
int l,
int r,
int x)
{
if(L<=l&&r<=R)
{
sum[x]+=C*(r-l+
1);
add[x]+=C;
return ;
}
int mid=(l+r)/
2;
pushdown(x,mid-l+
1,r-mid);
if(L<=mid) update(L,R,C,l,mid,x<<
1);
if(R>mid) update(L,R,C,mid+
1,r,x<<
1|
1);
pushup(x);
}
long long query (
int L,
int R,
int l,
int r,
int x)
{
if(L<=l&&r<=R)
{
return sum[x];
}
int mid = (l+r)>>
1;
pushdown(x,mid-l+
1,r-mid);
long long ans=
0;
if(L<=mid) ans+=query(L,R,l,mid,x<<
1);
if(R>mid ) ans+=query(L,R,mid+
1,r,x<<
1|
1);
return ans;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen(
"1.txt",
"r",stdin);
#endif
ios_base::sync_with_stdio(
false);
cin.tie(
0);
char c;
int x,y,z;
while(
cin>>n>>l)
{
mem(sum);
mem(add);
mem(a);
for(
int i=
1; i<=n; ++i)
cin>>a[i];
build(
1,n,
1);
while(l--)
{
cin>>c;
if(c==
'Q')
{
cin>>x>>y;
cout<<query(x,y,
1,n,
1)<<endl;
}
if(c==
'C')
{
cin>>x>>y>>z;
update(x,y,z,
1,n,
1);
}
}
}
return 0;
}