线段树(不带lazy)

多用于修改一个点的值

给一个求最大值模板

 1 const int maxn = 2e5+5;//数据大小
 2 
 3 struct Segment_tree{
 4     int L[maxn*4],R[maxn*4],val[maxn*4]; //4倍保证足够大
 5 
 6     void build(int pos,int l,int r,int *a){//1 1 n a
 7         L[pos] = l;
 8         R[pos] = r;
 9         if(l == r){
10             val[pos] = a[l]; //区间长度为1时的基础值
11             return ;
12         }
13         int mid = (l + r) >> 1;
14         build(pos<<1,l,mid,a);
15         build(pos<<1|1,mid+1,r,a);
16         val[pos] = max(val[pos<<1],val[pos<<1|1]); //取区间最大值
17     }
18 
19     void update(int pos,int l,int r,int v){//修改区间l,r的值为v
20         if(L[pos] == R[pos]){
21             val[pos] = v;
22             return;
23         }
24         val[pos] = max(val[pos],v); //取最大值
25         int mid = (L[pos] + R[pos]) >> 1;
26         if(r <= mid) update(pos<<1,l,r,v);
27         else if(l > mid) update(pos<<1|1,l,r,v);
28         else{
29             update(pos<<1,l,mid,v);
30             update(pos<<1|1,mid+1,r,v);
31         }
32     }
33 
34     int query(int pos,int l,int r){//查询l,r内的最大值
35         if(L[pos] == l && R[pos] == r){
36             return val[pos];
37         }
38         int mid = (L[pos] + R[pos]) >> 1;
39         if(r <= mid) return query(pos<<1,l,r);
40         else if(l > mid) return query(pos<<1|1,l,r);
41         else return max(query(pos<<1,l,mid),query(pos<<1|1,mid+1,r));
42     }
43 }tre;

 

posted @ 2017-08-04 11:04  yZi  阅读(276)  评论(0编辑  收藏  举报