一道入门级的区间更新的线段树。
区间更新与单点更新相比,有一个lazy优化。就是一旦找到那个可以更新的区间,将那个区间更新完之后就不再继续更新,只是做一个lzy标记,等到下一次更新或查询时到更低层次的节点时,再顺便更新。在更新的过程中要注意是直接赋值还是加上这个值。还有题目说了这道题要用64位整型。
再来谈一下我的代码需要注意的地方,首先是从0开始计数,用开左闭右开区间表示范围,所以在查询和更新时一定要注意下标的对应,用[a-1,b)区间代表要查询或更新的[a,b]区间。
代码(C++):
#include <iostream>
#include <cstdio>
#include <cstring>
#define MAX 100009
using namespace std;
__int64 sum[MAX<<2],res;
int num[MAX],lzy[MAX<<2];
void build(int v,int h,int r)
{
int m,chl,chr;
if(r-h==1)
{
sum[v]=num[h];
return;
}
m=(h+r)>>1;
chl=v<<1|1;
chr=(v<<1)+2;
build(chl,h,m);
build(chr,m,r);
sum[v]=sum[chl]+sum[chr];
}
void init(int n)
{
memset(lzy,0,sizeof(lzy));
build(0,0,n);
}
void push_down(int v,int h,int r)
{
int m,chl,chr;
m=(h+r)>>1;
chl=v<<1|1;
chr=(v<<1)+2;
if(lzy[v]!=0)
{
sum[chl]+=(__int64)(m-h)*lzy[v];
sum[chr]+=(__int64)(r-m)*lzy[v];
lzy[chl]+=lzy[v];
lzy[chr]+=lzy[v];
lzy[v]=0;
}
}
void update(int a,int b,int c,int v,int h,int r)
{
int m,chl,chr;
if(a>=r||b<=h) return;
if(a<=h&&b>=r)
{
sum[v]+=(__int64)(r-h)*c;
lzy[v]+=c;
return;
}
m=(h+r)>>1;
chl=v<<1|1;
chr=(v<<1)+2;
push_down(v,h,r);
update(a,b,c,chl,h,m);
update(a,b,c,chr,m,r);
sum[v]=sum[chl]+sum[chr];
}
void query(int a,int b,int v,int h,int r)
{
int m,chr,chl;
if(a>=r||b<=h) return;
if(a<=h&&b>=r)
{
res+=sum[v];
return;
}
m=(r+h)>>1;
chl=v<<1|1;
chr=(v<<1)+2;
push_down(v,h,r);
query(a,b,chl,h,m);
query(a,b,chr,m,r);
}
int main()
{
//freopen("in.txt","r",stdin);
int n,op,i,a,b,c;
char ch;
while(scanf("%d %d",&n,&op)!=EOF)
{
for(i=0;i<n;i++) scanf("%d",&num[i]);
init(n);
for(i=0;i<op;i++)
{
getchar();
scanf("%c",&ch);
if(ch=='Q')
{
scanf("%d %d",&a,&b);
res=0;
query(a-1,b,0,0,n);
printf("%I64d\n",res);
}else{
scanf("%d %d %d",&a,&b,&c);
update(a-1,b,c,0,0,n);
}
}
}
return 0;
}
题目( http://poj.org/problem?id=3468):
Time Limit: 5000MS | Memory Limit: 131072K | |
Case Time Limit: 2000MS |
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