-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsegment tree ( 1 ).cpp
66 lines (58 loc) · 1.74 KB
/
segment tree ( 1 ).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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include<bits/stdc++.h>
#define mx 100001
int arr[mx];
int tree[mx * 4];
using namespace std;
void init(int node, int b, int e)
{
if (b == e) {
tree[node] = arr[b];
return;
}
int Left = node * 2;
int Right = node * 2 + 1;
int mid = (b + e) / 2;
init(Left, b, mid);
init(Right, mid + 1, e);
tree[node] = tree[Left] + tree[Right];
}
int query(int node, int b, int e, int i, int j)
{
if (i > e || j < b)
return 0; //বাইরে চলে গিয়েছে
if (b >= i && e <= j)
return tree[node]; //রিলেভেন্ট সেগমেন্ট
int Left = node * 2; //আরো ভাঙতে হবে
int Right = node * 2 + 1;
int mid = (b + e) / 2;
int p1 = query(Left, b, mid, i, j);
int p2 = query(Right, mid + 1, e, i, j);
return p1 + p2; //বাম এবং ডান পাশের যোগফল
}
void update(int node, int b, int e, int i, int newvalue)
{
if (i > e || i < b)
return; //বাইরে চলে গিয়েছে
if (b >= i && e <= i) { //রিলেভেন্ট সেগমেন্ট
tree[node] = newvalue;
return;
}
int Left = node * 2; //আরো ভাঙতে হবে
int Right = node * 2 + 1;
int mid = (b + e) / 2;
update(Left, b, mid, i, newvalue);
update(Right, mid + 1, e, i, newvalue);
tree[node] = tree[Left] + tree[Right];
}
int main()
{
int n;
cin >> n;
for(int i=1;i<=n;i++) cin>> arr[i];
init(1, 1, n);
update(1, 1, n, 2, 0);
cout << query(1, 1, n, 1, 3) << endl;
update(1, 1, n, 2, 1);
cout << query(1, 1, n, 2, 2) << endl;
return 0;
}