Tang-Dreamoon's Blog

poj 3468

区间加减 区间求和

  题目链接:http://poj.org/problem?id=3468

  题目大意:区间加减,区间求和

  区间加减还是有很多要注意的地方:1、数组一定要开大。因为线段树正常的节点个数最大可能是4 * N 个,而因为会有 PUSH_DOWN () 的操作所以每个叶子节点会多两个儿子,所以我开了16 * N 个点。2、PUSH_DOWN () 操作很可能写错(汗~~~)L A Z Y 标记的意思是这个点已经进行过操作了,而孩子节点还没有。所以每当对一个点打一个 L A Z Y 标记时,还要修改这个点的权值。3、无论是 ADD () 还是 ASK () 都需要在开始的时候 PUSH_DOWN () 一发这很重要!!!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<algorithm>
using namespace std;
long long map[100100];
long long now[100100*16];
long long lazy[100100*16];
void build(int l,int r,int pos)
{
if(l==r) now[pos]=map[l];
else
{
int mid=(l+r)/2,lson=pos*2,rson=pos*2+1;
build(l,mid,lson),build(mid+1,r,rson);
now[pos]=now[lson]+now[rson];
}
}
void push_down(int l,int r,int pos)
{
int mid=(l+r)/2,lson=pos*2,rson=pos*2+1;
lazy[lson]+=lazy[pos],lazy[rson]+=lazy[pos];
now[lson]+=lazy[pos]*(mid-l+1),now[rson]+=lazy[pos]*(r-mid);
lazy[pos]=0;
}
void add(int l,int r,int pos,int fr,int to,int w)
{
if(lazy[pos]) push_down(l,r,pos);
if(l==fr&&r==to) lazy[pos]+=w,now[pos]+=(r-l+1)*lazy[pos];
else
{
int mid=(l+r)/2,lson=pos*2,rson=pos*2+1;
if(mid>=to)
{
add(l,mid,lson,fr,to,w);
}
else if(mid<fr)
{
add(mid+1,r,rson,fr,to,w);
}
else
{
add(l,mid,lson,fr,mid,w),add(mid+1,r,rson,mid+1,to,w);
}
now[pos]=now[lson]+now[rson];
}
}
long long ask(int l,int r,int pos,int fr,int to)
{
if(lazy[pos]) push_down(l,r,pos);
if(l==fr&&r==to) return now[pos];
else
{
int mid=(l+r)/2,lson=pos*2,rson=pos*2+1;
long long ans=0;
if(mid>=to)
{
ans=ask(l,mid,lson,fr,to);
}
else if(mid<fr)
{
ans=ask(mid+1,r,rson,fr,to);
}
else
{
ans=ask(l,mid,lson,fr,mid)+ask(mid+1,r,rson,mid+1,to);
}
return ans;
}
}
signed main(void)
{
int n,m;
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++) scanf("%lld",&map[i]);
build(1,n,1);
while(m--)
{
char c=getchar();
while(c!='Q'&&c!='C') c=getchar();
if(c=='Q')
{
int x,y;
scanf("%d%d",&x,&y);
printf("%lld\n",ask(1,n,1,x,y));
}
else
{
int x,y,z;
scanf("%d%d%d",&x,&y,&z);
add(1,n,1,x,y,z);
}
}
return 0;
}