-
Notifications
You must be signed in to change notification settings - Fork 212
/
Copy pathsegment-tree.cpp
50 lines (49 loc) · 1.1 KB
/
segment-tree.cpp
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
vector<int>seg;
#define ZERO 0 // define the zero value,its 0 for sum,1 for product
void merge(const int &a,const int &b,int &c)
{
c=max(a,b);
c=min(a,b);
c=a+b;
c=__gcd(a,b); // use any of merge method
}
void build(int pos,int ss,int se,vector<int>&a)
{
if(pos==0)
seg.resize(4*(se+1)+1);
if(ss==se)
{
seg[pos]=a[ss];
return;
}
int mid=(ss+se)/2;
build(2*pos+1,ss,mid);
build(2*pos+2,mid+1,se);
merge(seg[2*pos+1],seg[2*pos+2],seg[pos])
}
int query(int pos,int ss,int se,int l,int r)
{
if(l>se || r < ss)
return ZERO;
if(ss >=l && se<=r)
return seg[pos];
int mid=(ss+se)/2;
int q1=query(2*pos+1,ss,mid,l,r);
int q2=query(2*pos+2,mid+1,se,l,r);
int ans;merge(q1,q2,ans);
return ans;
}
void update(int pos,int ss,int se,int index,int value)
{
if(index <ss || index >se)
return ;
if(ss==se)
{
seg[pos]=value;
return ;
}
int mid=(ss+se)/2;
update(2*pos+1,ss,mid,index,value);
update(2*pos+2,mid+1,se,index,value);
merge(seg[2*pos+1],seg[2*pos+2],seg[pos]);
}