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 4Sample Output
4 55 9 15Hint
代码:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long ll;
const int maxn = 100050;
ll digit[maxn];
struct node
{
ll sum,lazy;
int left,right;
}tree[maxn*4];
//线段树的建立
void build(int k,int l,int r)
{
tree[k].left = l;
tree[k].right = r;
tree[k].lazy = 0;//懒惰标记为 0 因为是区间更新所以容易超时这个时候就应该lazy标记
if(l==r)
{
tree[k].sum = digit[l];
return ;
}
int mid = (l+r)/2;
build(k<<1,l,mid);
build(k<<1|1,mid+1,r);
tree[k].sum = tree[k<<1].sum + tree[k<<1|1].sum;
}
//释放懒惰标记
void pushlazy(int k)
{
if(tree[k].lazy)
{
tree[k<<1].lazy += tree[k].lazy;
tree[k<<1|1].lazy += tree[k].lazy;
tree[k<<1].sum +=tree[k].lazy*(tree[k<<1].right-tree[k<<1].left+1); //这边和下面那一行要注意的就是是!!tree[k].lazy*
tree[k<<1|1].sum +=tree[k].lazy*(tree[k<<1|1].right-tree[k<<1|1].left+1);
tree[k].lazy = 0;
}
}
//线段树的更新
void update(int k,int l,int r,ll val)
{
if(tree[k].left == l && tree[k].right == r)
{
tree[k].lazy +=val; //因为下面的其他节点都还没有加上他们所应该的值所以不能为0
tree[k].sum += val * (r-l+1); //这一步是因为要加上这个的值
return ;
}
if(tree[k].left == tree[k].right) return; //因为是叶子节点所以说不用再向下释放了直接可以return
pushlazy(k);//释放lazy标记
int mid = (tree[k].left + tree[k].right)>>1;
if(r<=mid)
update(k<<1,l,r,val);
else if(l>mid)
update(k<<1|1,l,r,val);
else
{
update(k<<1,l,mid,val);
update(k<<1|1,mid+1,r,val);
}
tree[k].sum = tree[k<<1].sum + tree[k<<1|1].sum;//这步要记得加
return;
}
ll query(int k,int l,int r)
{
if(tree[k].left == l && r == tree[k].right)
{
return tree[k].sum;
}
pushlazy(k);
ll ans = 0;
int mid = (tree[k].left + tree[k].right)>>1;
if(r<=mid)
ans+=query(k<<1,l,r);
else if(l>mid)
ans+=query(k<<1|1,l,r);
else
{
ans+=query(k<<1,l,mid);
ans+=query(k<<1|1,mid+1,r);
}
return ans;
}
int main()
{
int n,q,x,y;ll z;
scanf("%d%d",&n,&q);
for(int i = 1;i<=n;i++)
scanf("%lld",&digit[i]);
build(1,1,n);
while(q--)
{
char s[5];
scanf("%s",s);
if(s[0] == 'Q')
{
scanf("%d%d",&x,&y);
printf("%lld\n",query(1,x,y));
}else
{
scanf("%d%d%lld",&x,&y,&z);
update(1,x,y,z);
}
}
return 0;
}
query其他写法
ll query(int k,int l,int r)
{
if(tree[k].left >= l && tree[k].right <=r)
{
return tree[k].sum;
}
pushlazy(k);
ll ans = 0;
int mid = (tree[k].left + tree[k].right)>>1;
if(l<=mid)
ans+=query(k<<1,l,r);
if(r>mid)
ans+=query(k<<1|1,l,r);
return ans;
}