Description
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.
Input
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.
Output
You need to answer all Q commands in order. One answer in a line.
Sample Input
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 4
Sample Output
4
55
9
15
Hint
线段树的区间更新和区间和的查询,加了lazy的优化,用的还是不熟练,太菜。。。有几处错误gg,这里标注一下,以后长点记性:
( 1 ) 跟set不一样,这里用的是add,是在给定区间上的每个数加上一个数,pushdown里s[lc]和s[rc]加的是下推了的lazy(s[d].lazy),而不是lc和rc的lazy(s[lc).lazy、s[rc].lazy),(s[lc].sum += (s[d].lazy * (m - l + 1)); s[rc].sum += (s[d].lazy * (r - m));)。
( 2 ) query里不需要pushup;
代码如下:
<cstdio>
#include<algorithm>
#include<cstring>
#define ll long long
using namespace std;
typedef struct node
{
ll sum,lazy;
}node;
const int maxn = 100000 + 5;
const int INF = 1 << 30;
node s[maxn << 4];
ll a[maxn];
void pushdown(int d,int l,int r)
{
int lc = d * 2,rc = d * 2 + 1,m = l + (r - l) / 2;
s[lc].lazy += s[d].lazy;
s[rc].lazy += s[d].lazy;
s[lc].sum += (s[d].lazy * (m - l + 1));
s[rc].sum += (s[d].lazy * (r - m));
s[d].lazy = 0;
}
void pushup(int d,int l,int r)
{
s[d].sum = s[d * 2].sum + s[d * 2 + 1].sum;
}
void build(int d,int l,int r)
{
s[d].lazy = 0;
if(l == r)
{
s[d].sum = a[l];
return;
}
int m = l + (r - l) / 2;
build(d * 2,l,m);
build(d * 2 + 1,m + 1,r);
pushup(d,l,r);
}
void update(int d,int x,int y,int l,int r,int v)
{
if(x <= l && r <= y)
{
s[d].lazy += v;
s[d].sum += (v*(r - l + 1));
return;
}
int m = l +(r - l) / 2;
if(s[d].lazy) pushdown(d,l,r);
if(x <= m) update(d * 2,x,y,l,m,v);
if(m < y) update(d * 2 + 1,x,y,m + 1,r,v);
pushup(d,l,r);
}
ll query(int d,int x,int y,int l,int r)
{
ll ss = 0;
if(x <= l && r <= y)
{
ss += s[d].sum;
return ss;
}
int m = l + (r - l) / 2;
if(s[d].lazy) pushdown(d,l,r);
if(x <= m) ss += query(d * 2,x,y,l,m);
if(m < y) ss += query(d * 2 + 1,x,y,m + 1,r);
return ss;
}
int main()
{
int n,q,x,y,v;
char p;
scanf("%d %d",&n,&q);
for(int i = 1;i <= n; ++i) scanf("%lld",&a[i]);
build(1,1,n);
for(int i = 0;i < q; ++i)
{
scanf(" %c",&p);
if(p == 'Q')
{
scanf("%d %d",&x,&y);
printf("%lld\n",query(1,x,y,1,n));
}
else if(p == 'C')
{
scanf("%d %d %d",&x,&y,&v);
update(1,x,y,1,n,v);
}
}
return 0;
}
本文介绍了一种使用线段树进行区间更新和区间和查询的方法,并通过具体实例展示了如何实现这一算法。讨论了懒惰传播(lazy propagation)优化技巧,避免不必要的节点更新,提高效率。

被折叠的 条评论
为什么被折叠?



