-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathsegmentTree.cpp
More file actions
127 lines (102 loc) · 2.22 KB
/
Copy pathsegmentTree.cpp
File metadata and controls
127 lines (102 loc) · 2.22 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
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
struct segTree
{
int size;
vector<long long int> sums;
void init(int n)
{
size = 1;
while (size < n)
{
size <<= 1;
}
sums.resize(2 * size);
}
void set(int i, int v, int x, int lx, int rx)
{
if (rx - lx == 1)
{
sums[x] = v;
return;
}
int m = (lx + rx) / 2;
if (i < m)
{
set(i, v, 2 * x + 1, lx, m);
}
else
{
set(i, v, 2 * x + 2, m, rx);
}
sums[x] = sums[2 * x + 1] + sums[2 * x + 2];
}
void set(int i, int v)
{
set(i, v, 0, 0, size);
}
long long int sum(int l, int r, int x, int lx, int rx)
{
if (lx >= r || l >= rx)
{
return 0;
}
if (lx >= l && rx <= r)
return sums[x];
int mid = (lx + rx) / 2;
long long int s1, s2;
s1 = sum(l, r, 2 * x + 1, lx, mid);
s2 = sum(l, r, 2 * x + 2, mid, rx);
return s1 + s2;
}
long long int sum(int l, int r)
{
return sum(l, r, 0, 0, size);
}
void build(vector<int> &a, int x, int lx, int rx)
{
if ((rx - lx) == 1)
{
if (lx < (int)(a.size()))
{
sums[x] = a[lx];
}
return;
}
int m = (lx + rx) / 2;
build(a, 2 * x + 1, lx, m);
build(a, 2 * x + 2, m, rx);
sums[x] = sums[2 * x + 1] + sums[2 * x + 2];
}
void build(vector<int> &a)
{
build(a, 0, 0, size);
}
};
int main()
{
segTree s;
int n;
cout<<"Enter the size of array\n";
cin>>n;
s.init(n);
cout<<"Enter the values\n";
vector<int> v(n);
for(auto &x: v) cin>>x;
s.build(v);
int l,r;
char c;
bool again = true;
while (again)
{
cout << "enter starting index and number of values to calculate sum\n";
cin>>l>>r;
r+=l;
cout<<s.sum(l,r)<<'\n';
cout<<"To calculate sum again press y and press n to exit\n";
cin>>c;
again = (c == 'y')? true : false;
}
return 0;
}