POJ3468(线段树区间求和+区间查询)

时间:2023-03-10 02:12:18
POJ3468(线段树区间求和+区间查询)

https://vjudge.net/contest/66989#problem/C

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<bits/stdc++.h>
#include<iostream>
#include<stdio.h>
#include<string.h>
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
using namespace std;
const int maxn=;
long long sum[maxn<<],add[maxn<<];
void pushup(int rt)
{
sum[rt]=sum[rt<<]+sum[rt<<|];
}
void pushdown(int rt,int ln,int rn)
{
if(add[rt])
{
sum[rt<<]+=add[rt]*ln;
sum[rt<<|]+=add[rt]*rn;
add[rt<<]+=add[rt];
add[rt<<|]+=add[rt];
add[rt]=;
}
}
void build(int l,int r,int rt)
{
if(r==l)
{
scanf("%lld",&sum[rt]);
return;
}
int m=(l+r)>>;
build(lson);
build(rson);
pushup(rt);
}
void update(int L,int R,int c,int l,int r,int rt)
{
if(L<=l&&R>=r)
{
sum[rt]+=(long long)c*(r-l+);
add[rt]+=c;
return;
}
int m=(l+r)>>;
pushdown(rt,m-l+,r-m);
if(L<=m)
update(L,R,c,lson);
if(R>m)
update(L,R,c,rson);
pushup(rt);
}
long long query(int L,int R,int l,int r,int rt)
{
if(L<=l&&R>=r)
{
return sum[rt];
}
int m=(r+l)>>;
pushdown(rt,m-l+,r-m);
long long ans=;
if(L<=m)
ans+=query(L,R,lson);
if(R>m)
ans+=query(L,R,rson);
return ans;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie();
int n,m,x,y,z,q;
char h;
while(~scanf("%d%d",&n,&q))
{
memset(sum,,sizeof sum);
memset(add,,sizeof add);
build(,n,);
for(int i=;i<=q;i++)
{
getchar();
scanf("%c",&h);
if(h=='Q')
{
scanf("%d%d",&x,&y);
cout<<query(x,y,,n,)<<endl;
}
else if(h=='C')
{
scanf("%d%d%d",&x,&y,&z);
update(x,y,z,,n,);
}
}
}
return ;
}

注意点:

是道裸题了

BUT 在输入数据的时候 ,scanf("%lld",&sum[rt]);一开始把它写成%d了,害我WA了好几发;

sum[rt]+=(long long)c*(r-l+1); 一开始没注意把数据转化为long long(>人<;)。

以后一定要注意呀!