Time Limit: 5000MS | Memory Limit: 131072K | |
Total Submissions: 87678 | Accepted: 27225 | |
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
线段树即可,,数据改成longlong,也是区间更新,单点查询。
#include
#include
#include
using namespace std;
#define LL long long
#define lson l,mid,i*2
#define rson mid+1,r,i*2+1
const LL MAXN=100000;
LL num[MAXN];
struct tree
{
LL l,r;
LL sum;
LL lazy;
} tr[MAXN*3];
void build(LL l,LL r,LL i)
{
tr[i].l=l;
tr[i].r=r;
tr[i].lazy=0;
if(l==r)
{
tr[i].sum=num[l];
return;
}
LL mid=(l+r)/2;
build(lson);
build(rson);
tr[i].sum=tr[i*2].sum+tr[i*2+1].sum;
}
void add(LL l,LL r,LL i,LL c)
{
if(tr[i].l==l&&tr[i].r==r)
{
tr[i].lazy+=c;
return;
}
tr[i].sum+=c*(r-l+1);
LL mid=(tr[i].l+tr[i].r)/2;
if(r<=mid)
add(l,r,i*2,c);
else if(l>mid)
add(l,r,i*2+1,c);
else
{
add(lson,c);
add(rson,c);
}
}
LL query(LL l,LL r,LL i)
{
if(tr[i].l==l&&tr[i].r==r)
return tr[i].sum+(r-l+1)*tr[i].lazy;
tr[i].sum+=(tr[i].r-tr[i].l+1)*tr[i].lazy;
LL mid=(tr[i].l+tr[i].r)/2;
add(tr[i].l,mid,i*2,tr[i].lazy);
add(mid+1,tr[i].r,i*2+1,tr[i].lazy);
tr[i].lazy=0;
if(r<=mid)
return query(l,r,i*2);
else if(l>mid)
return query(l,r,i*2+1);
else
return query(lson)+query(rson);
}
int main()
{
LL n,t,a,b,c;
char ch[2];
scanf("%lld%lld",&n,&t);
for(LL i=1; i<=n; i++)
scanf("%lld",&num[i]);
build(1,n,1);
for(LL i=1; i<=t; i++)
{
scanf("%s",ch);
if(ch[0]=='C')
{
scanf("%lld%lld%lld",&a,&b,&c);
add(a,b,1,c);
}
else
{
scanf("%lld%lld",&a,&b);
printf("%lld\n",query(a,b,1));
}
}
return 0;
}