题目链接:http://poj.org/problem?id=3468
题型:线段树
以下是参考大神的代码写的!!
#include<iostream>
#include<string>
#include<cstring>
#include<algorithm>
#include<cstdio>
#include<cmath>
#include<cctype>
#include<iomanip>
#define Lson left ,mid, rt<<1
#define Rson mid+1,right,rt<<1|1
#define MID (left+right)>>1
using namespace std;
typedef long long LL;
const int maxn=100000;
LL sum[maxn<<2];
LL add[maxn<<2];
void PushUp(int rt) {
sum[rt]=sum[rt<<1]+sum[rt<<1|1];
}
void PushDown(int rt){
if(sum[rt]){
sum[rt<<1]=sum[rt];
sum[rt<<1|1]=sum[rt];
sum[rt]=0;
}
}
void PushDown(int rt,int m) {
if(add[rt]) {
add[rt<<1]+=add[rt];
add[rt<<1|1]+=add[rt];
sum[rt<<1]+=add[rt]*(m-(m>>1));
sum[rt<<1|1]+=add[rt]*(m>>1);
add[rt]=0;
}
}
void build(int left,int right,int rt) {
add[rt]=0;
if(left==right) {
scanf("%lld",sum+rt);
return;
}
int mid=MID;
build(Lson);
build(Rson);
PushUp(rt);
}
void update(int l,int r,int v,int left,int right,int rt) {
if(l<=left&&r>=right) {
add[rt]+=(LL)v;
sum[rt]+=(LL)v*(right-left+1);
return;
}
PushDown(rt,right-left+1);
int mid=MID;
if(l<=mid) update(l,r,v,Lson);
if(r> mid) update(l,r,v,Rson);
PushUp(rt);
}
LL query(int l,int r,int left,int right,int rt) {
if(l<=left&&r>=right)
return sum[rt];
PushDown(rt,right-left+1);
int mid=MID;
LL ret=0;
if(l<=mid) ret+=query(l,r,Lson);
if(r>mid) ret+=query(l,r,Rson);
return ret;
}
int main() {
int n, m;
scanf("%d%d",&n,&m);
build(1,n,1);
while(m--) {
char a[3];
scanf("%s",a);
if(a[0]=='Q') {
int x,y;
scanf("%d%d",&x,&y);
printf("%lld\n",query(x,y,1,n,1));
}
else if(a[0]=='C') {
int x,y,z;
scanf("%d%d%d",&x,&y,&z);
update(x,y,z,1,n,1);
}
}
return 0;
}