Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- struct node {
- int value, lb, rb;
- node *L, *R;
- node(int _lb, int _rb) { // constructor (konsturktor so parametri)
- lb = _lb;
- rb = _rb;
- if(lb == rb) {
- value = 0;
- }
- else {
- int mid = (lb + rb) / 2;
- L = new node(lb, mid);
- R = new node(mid + 1, rb);
- value = L->value + R->value;
- }
- }
- int query(int i, int j) {
- if(i <= lb and rb <= j) {
- return value;
- }
- // i j l r i j
- if(j < lb or rb < i) {
- return 0;
- }
- return L->query(i, j) + R->query(i, j);
- }
- void update(int idx, int new_value) {
- if(lb == rb) {
- value = new_value;
- return;
- }
- if(idx >= R->lb) {
- R->update(idx, new_value);
- }
- else {
- L->update(idx, new_value);
- }
- value = L->value + R->value;
- }
- };
- int main() {
- int n;
- cin >> n;
- node * segment_tree = new node(0, n - 1);
- cout << segment_tree->query(0, n - 1) << endl;
- segment_tree->update(0, 1);
- segment_tree->update(1, 2);
- segment_tree->update(3, 3);
- for(int i = 0; i < n; i++) {
- cout << segment_tree->query(i, i) << " " ;
- }
- return 0;
- }
- /*
- 5
- 1 2 3 4 5
- 5
- **/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement