-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSegmentTree.cpp
More file actions
87 lines (63 loc) · 1.29 KB
/
SegmentTree.cpp
File metadata and controls
87 lines (63 loc) · 1.29 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
// SegmentTree.cpp : Ce fichier contient la fonction 'main'. L'exécution du programme commence et se termine à cet endroit.
//
#include <iostream>
#include <vector>
using namespace std;
#define ll long long int
struct segtree {
vector<ll> tree;
ll N;
ll _n;
void init(int n) {
ll size = 1;
while (size < n) {
size *= 2;
}
N = size - 1;
tree.resize(2 * size);
for (int i = 0; i < tree.size(); i++) {
tree[i] = 0;
}
}
void build(vector<ll> p) {
_n = p.size();
for (int i = 0; i < p.size(); i++) {
add(i, p[i]);
}
}
ll sumperf(int a, int b, int k, int x, int y) {
if (b < x || a > y) return 0;
if (a <= x && y <= b) {
return tree[k];
}
int d = (x + y) / 2;
return sumperf(a, b, 2 * k, x, d) + sumperf(a, b, 2 * k + 1, d + 1, y);
}
ll get_sum(int a, int b) {
return sumperf(a, b, 1, 0, N);
}
void add(ll k, ll x) {
k += _n + ((tree.size() / 2) - _n);
tree[k] += x;
for (k /= 2; k >= 1; k /= 2) {
tree[k] = tree[2 * k] + tree[2 * k + 1];
}
}
};
int main()
{
ll n, q;
cin >> n ;
vector<ll>p(n);
for (int i = 0; i < n; i++) {
cin >> p[i];
}
segtree seg;
seg.init(n);
seg.build(p);
cout << seg.get_sum(0, 4) << endl;
}
/*
5
5 3 1 5 2
*/