一开始写的时候就没有太注意更新 的部分,,
注意:要一直保留向下的更新,
要回溯更新。
#include<iostream>
#include<cstdio>
using namespace std;
#define N 100010
int n,q;
int go[N];
struct my
{
int left,right;
int mid;
long long value;
long long add;
}t[N*4];
void build(int cur,int l,int r)
{
t[cur].left=l;
t[cur].right=r;
t[cur].mid=(l+r)>>1;
t[cur].value=t[cur].add=0;
if (l!=r)
{
build(cur<<1,l,t[cur].mid);
build(cur<<1|1,t[cur].mid+1,r);
t[cur].value=t[cur<<1].value+t[cur<<1|1].value;
}
else
{
t[cur].value=go[l];
}
}
void update(int cur,int l,int r,long long v)
{
if (t[cur].left==l && t[cur].right==r)
{
t[cur].add+=v;
t[cur].value+=v*(r-l+1);
return ;
}
int L=cur<<1,R=cur<<1|1;
if (t[cur].add!=0)
{
t[L].add+=t[cur].add;
t[R].add+=t[cur].add;
t[L].value+=t[cur].add*(t[L].right-t[L].left+1);
t[R].value+=t[cur].add*(t[R].right-t[R].left+1);
t[cur].add=0;
}
if (r<=t[cur].mid)
update(L,l,r,v);
else if (l>t[cur].mid)
update(R,l,r,v);
else
{
update(L,l,t[cur].mid,v);
update(R,t[cur].mid+1,r,v);
}
t[cur].value=t[L].value+t[R].value;
}
long long find(int cur,int l,int r)
{
if (l==t[cur].left && r==t[cur].right)
{
return t[cur].value;
}
int L=cur<<1,R=cur<<1|1;
if (t[cur].add!=0) //一直保持向下更新
{
t[L].add+=t[cur].add;
t[R].add+=t[cur].add;
t[L].value+=t[cur].add*(t[L].right-t[L].left+1);
t[R].value+=t[cur].add*(t[R].right-t[R].left+1);
t[cur].add=0;
}
long long ans=0;
if (r<=t[cur].mid)
ans=find(L,l,r);
else if (l>t[cur].mid)
ans=find(R,l,r);
else
ans=find(L,l,t[cur].mid)+find(R,t[cur].mid+1,r);
t[cur].value=t[L].value+t[R].value; //像这种地方都向上更新一下吧,
return ans;
}
int main()
{
freopen("in.txt","r",stdin);
int i,j;
long long k;
scanf("%d%d",&n,&q);
for (i=1;i<=n;++i)
scanf("%d",go+i);
build(1,1,n);
while (q--)
{
char c;
scanf("\n%c",&c);
if (c=='Q')
{
scanf("%d%d",&i,&j);
//cout<<find(1,i,j)<<endl;
printf("%lld\n",find(1,i,j));
}
else
{
scanf("%d%d%lld",&i,&j,&k);
update(1,i,j,(long long)k);
}
}
return 0;
}
Time Limit: 5000MS | Memory Limit: 131072K | |
Total Submissions: 42738 | Accepted: 12462 | |
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
Hint