-线段树用来查询区间和和单点更新
-一般题目中有“Q次查询,区间更新”可以考虑用线段树,因为如果暴力更新会超时,而线段树的时间复杂度比较小。
https://mp.weixin.qq.com/s/I5UC97B6YD-nqBsNgJyOAw
这是我觉得写的比较好的线段树的入门解析,菜鸟我尝试理解了一下
然后值得注意的点就是
**
----lazy[]数组记录的是 当前节点的子节点 还没有更新的值
**
而且lazy数组更新的时候给下一个树的左右孩子打上标记,因为孩子的孩子还没有更新,所以先打上标记,待查询时再更新.
–线段树每个节点的含义是一个区间和
我理解的线段树的打码的思路
定义数组1存区间和,数组2存标记
【1】建立线段树
如果l=r,则
输入数据且初始化标记
否则,递归,直到l==r,
加上左右孩子,求区间和,将结果记录在t数组里面】
【2】使标记下压
【使该标记中没有更新的数据更新,
左右孩子打上标记
左右孩子的区间和更新
初始化该标记】
【3】更新区间
【如果要更新的区间在(1~n),使区间和更新,先打上标记,先不更新区间里面的数据
不然就求mid,下压标记,递归更新左右孩子,更新区间和】
【4】查询区间和
【如果查询的区间在(1~n),直接输出区间和,
不然就求mid,下压标记,递归求和】
【5】主函数【建立线段树,查询,更新】
例题
A Simple Problem with Integers
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.
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
#include<iostream>
using namespace std;
const int maxn=100010;
#define lson l,m,rt*2
#define rson m+1,r,rt*2+1
#define pushup(rt) t[rt]=t[rt*2]+t[rt*2+1];
long long int t[maxn*4],lazy[maxn*4];
void build(int l,int r,int rt){
lazy[rt]=0;
if(l==r) {
cin>>t[rt];
return ;
}
int m=(l+r)/2;
build(lson);
build(rson);
pushup(rt);
}
void pushdown(int l,int r,int rt){
if(lazy[rt]){
lazy[rt*2]+=lazy[rt];
lazy[rt*2+1]+=lazy[rt];
t[rt*2]+=l*lazy[rt];
t[rt*2+1]+=r*lazy[rt];
lazy[rt]=0;
}
}
void update(int L,int R,int C,int l,int r,int rt){
if(L<=l&&r<=R){
t[rt]+=(r-l+1)*C;
lazy[rt]+=C;
return ;
}
int m=(l+r)/2;
pushdown(m-l+1,r-m,rt);
if(L<=m) update(L,R,C,lson);
if(R>m) update(L,R,C,rson);
pushup(rt);
}
long long int query(int L,int R,int l,int r,int rt){
if(L<=l&&r<=R){
return t[rt];
}
int m=(l+r)/2;
pushdown(m-l+1,r-m,rt);
long long int ans=0;
if(L<=m) ans+=query(L,R,lson);
if(R>m) ans+=query(L,R,rson);
return ans;
}
int main(){
int n,m;
cin>>n>>m;
build(1,n,1);
char c;
int a,b;
long long int g;
while(m--){
cin>>c;
if(c=='C') {
cin>>a>>b>>g;
update(a,b,g,1,n,1);
}
else{
cin>>a>>b;
cout<<query(a,b,1,n,1)<<endl;
}
}
return 0;
}