-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathsegment_tree.cpp
More file actions
150 lines (106 loc) · 2.15 KB
/
segment_tree.cpp
File metadata and controls
150 lines (106 loc) · 2.15 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
/*
segment tree
You have given an array A of n elements. Your task is to process q queries of the following types.
1 i x : Update the value at position i to x.
2 i j : Print the sum of values in the range [i, j].
*/
#include<bits/stdc++.h>
using namespace std;
typedef long long int ll; //g++ ll.cpp -o ll.exe
typedef long double ld;
typedef pair<ll,ll> iii; //all elements to 0
const ll mod =1e9+7;
struct node
{
ll x;
};
vector<node> g;
vector<ll> ar;
node merge(node a,node b)
{
node temp;
temp.x=a.x+b.x;
return temp;
}
void build(ll index,ll l,ll r)
{
if(l==r)
{
node tt;
tt.x=ar[l];
g[index]=tt;
return;
}
ll mid;
mid=(l+r)/2;
build(2*index,l,mid);
build(2*index+1,mid+1,r);
g[index]=merge(g[2*index],g[2*index+1]);
}
void update(ll index,ll l,ll r,ll pos,ll value)
{
if((pos<l)|| (pos>r))
return;
if(l==r)
{
//cout<<index<<endl;
node tt;
tt.x=value;
g[index]=tt;
ar[l]=value;
return;
}
ll mid;
mid=(l+r)/2;
update(2*index,l,mid,pos,value);
update(2*index+1,mid+1,r,pos,value);
g[index]=merge(g[2*index],g[2*index+1]);
}
node query(ll index,ll l,ll r,ll lq,ll rq)
{
node ans;
ans.x=0;
if(lq> r || rq<l)
return ans;
if(lq<=l && rq>=r)
return(g[index]);
ll mid=(l+r)/2;
ans=merge(query(2*index,l,mid,lq,rq),query(2*index+1,mid+1,r,lq,rq));
return(ans);
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
ll n,q;
cin>>n>>q;
g.resize(4*n+6);
ar.resize(n+1);
for(ll i=1;i<=n;i++)
cin>>ar[i];
build(1,1,n);
while(q--)
{
ll t;
cin>>t;
if(t==1)
{
ll i,x;
cin>>i>>x;
update(1,1,n,i,x);
}
if(t==2)
{
ll lq,rq;
cin>>lq>>rq;
node temp;
temp=query(1,1,n,lq,rq);
cout<<temp.x<<endl;
}
}
return 0;
}