这是一道模板题。
给定数列 a[1],a[2],…,a[n],你需要依次进行 q 个操作,操作有两类:
1 l r x:给定 l,r,x,对于所有 i∈[l,r],将 a[i] 加上 x(换言之,将 a[l],a[l+1],…,a[r] 分别加上 x);
2 l r:给定 l,r,求 ∑ri=la[i] 的值(换言之,求 a[l]+a[l+1]+⋯+a[r] 的值)。
输入格式
第一行包含 2 个正整数 n,q,表示数列长度和询问个数。保证 1≤n,q≤10^6。
第二行 n 个整数 a[1],a[2],…,a[n],表示初始数列。保证 |a[i]|≤10^6。
接下来 q 行,每行一个操作,为以下两种之一:
1 l r x:对于所有 i∈[l,r],将 a[i] 加上 x;
2 l r:输出 ∑ri=la[i] 的值。保证 1≤l≤r≤n, |x|≤106。
输出格式
对于每个 2 l r 操作,输出一行,每行有一个整数,表示所求的结果。
样例
Input
5 10
2 6 6 1 1
2 1 4
1 2 5 10
2 1 3
2 2 3
1 2 2 8
1 2 3 7
1 4 4 10
2 1 2
1 4 5 6
2 3 4
Output
15
34
32
33
50
数据范围与提示
对于所有数据,1≤n,q≤106, |a[i]|≤106, 1≤l≤r≤n, |x|≤106。
嗯…我就想存个模板…
代码:
#include<stdio.h>
#include<string.h>
typedef long long ll;
ll tree[5000000],lazy[5000000];
void build(int start,int end,int node)
{
if(start==end)
scanf("%lld",&tree[node]);
else
{
int mid=(start+end)/2;
build(start,mid,2*node);
build(mid+1,end,2*node+1);
tree[node]=tree[2*node]+tree[2*node+1];
}
}
void pushdown(int l,int node)
{
if(lazy[node])
{
lazy[2*node]+=lazy[node];
lazy[2*node+1]+=lazy[node];
tree[2*node]+=lazy[node]*(l-(l/2));
tree[2*node+1]+=lazy[node]*(l/2);
lazy[node]=0;
}
}
void update(int start,int end,int node,int L,int R,int c)
{
if(L<=start&&R>=end)
{
tree[node]+=(ll)(end-start+1)*c;
lazy[node]+=c;
}
else
{
pushdown(end-start+1,node);
int mid=(start+end)/2;
if(L<=mid)
update(start,mid,2*node,L,R,c);
if(R>mid)
update(mid+1,end,2*node+1,L,R,c);
tree[node]=tree[2*node]+tree[2*node+1];
}
}
long long query(int start,int end,int node,int L,int R)
{
if(L<=start&&R>=end)
return tree[node];
else
{
pushdown(end-start+1,node);
int mid=(start+end)/2;
long long s=0;
if(L<=mid)
s+=query(start,mid,2*node,L,R);
if(R>mid)
s+=query(mid+1,end,2*node+1,L,R);
return s;
}
}
int main()
{
ll n,q,i;
scanf("%lld %lld",&n,&q);
build(1,n,1);
for(i=0; i<q; i++)
{
ll a,b,c,d;
scanf("%lld",&a);
if(a==1)
{
scanf("%lld %lld %lld",&b,&c,&d);
update(1,n,1,b,c,d);
}
else
{
scanf("%lld %lld",&b,&c);
printf("%lld\n",query(1,n,1,b,c));
}
}
return 0;
}