1.题目描述:点击打开链接
2.解题思路:本题是线段树的区间修改基础题。
3.代码:
#include<iostream>
#include<algorithm>
#include<cassert>
#include<string>
#include<sstream>
#include<set>
#include<bitset>
#include<vector>
#include<stack>
#include<map>
#include<queue>
#include<deque>
#include<cstdlib>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<ctime>
#include<cctype>
#include<complex>
#include<functional>
#pragma comment(linker, "/STACK:1024000000,1024000000")
using namespace std;
#define me(s) memset(s,0,sizeof(s))
#define rep(i,n) for(int i=0;i<(n);i++)
typedef long long ll;
typedef unsigned int uint;
typedef unsigned long long ull;
typedef pair <ll, ll> P;
#define lid (id<<1)
#define rid (id<<1|1)
const int N=100000+10;
int a[N];
struct Node
{
int l,r;
ll lazy;
ll sum;
int mid(){return l+(r-l)/2;}
void fun(ll add)
{
lazy+=add;
sum+=(r-l+1)*add;
}
}tree[N*4];
void pushdown(int id)
{
if(tree[id].lazy)
{
tree[lid].fun(tree[id].lazy);
tree[rid].fun(tree[id].lazy);
tree[id].lazy=0;
}
}
void pushup(int id)
{
tree[id].sum=tree[lid].sum+tree[rid].sum;
}
void build(int id,int L,int R)
{
tree[id].l=L,tree[id].r=R;
if(L==R){tree[id].sum=a[L];return;}
int M=tree[id].mid();
build(lid,L,M);
build(rid,M+1,R);
pushup(id);
}
void update(int L,int R,int id,int val)
{
int l=tree[id].l,r=tree[id].r;
if(L<=l&&r<=R){tree[id].fun(val);return;}
pushdown(id);
int mid=tree[id].mid();
if(L<=mid)update(L,R,lid,val);
if(R>mid)update(L,R,rid,val);
pushup(id);
}
ll query(int L,int R,int id)
{
int l=tree[id].l,r=tree[id].r;
if(L<=l&&r<=R)return tree[id].sum;
pushdown(id);
int mid=tree[id].mid();
ll s1=0,s2=0;
if(L<=mid)s1=query(L,R,lid);
if(R>mid)s2=query(L,R,rid);
pushup(id);
return s1+s2;
}
int n,q;
int main()
{
while(~scanf("%d%d",&n,&q))
{
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
build(1,0,n-1);
char cmd[2];
int a,b;
while(q--)
{
scanf("%s%d%d",cmd,&a,&b);
if(cmd[0]=='Q')
{
printf("%lld\n",query(a-1,b-1,1));
}
else
{
int x;scanf("%d",&x);
update(a-1,b-1,1,x);
}
}
}
}