Search
 
SCRIPT & CODE EXAMPLE
 

CPP

how to make a segment tree in c++

#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
bool isPower(long long n)
{
    long long f = 1;
 
    while (f <= n) {
        if (f == n) {
            return false;
        }
        else {
            f *= 2;
        }
    }
 
    return true;
 
 
 
 
}
int main()
{
    long long n;
    long long t;
 
    cin >> n >> t;
    vector<unsigned long long>v(n * 2);
    long long k;
    for (long long i = n; i < n*2; i++) {
        cin >> k;
        v[i] = k;
    }
    for (long long i = n - 1; i > 0; i--) {
        v[i] = v[2 * i] + v[2 * i + 1];
 
    }
 
    unsigned long long i;
    unsigned long long j;
    unsigned long long x = 1;
    unsigned long long sum = 0;
    unsigned long long sum1 = 0;
    long long zz;
    for (long long l = 0; l < t; l++) {
        sum = 0;
        x = 1;
        sum1 = 0;
        cin >> i;
        cin >> j;
 
        i += n - 1;
        j += n - 1;
        zz = i;
        if (i == j) {
            cout << v[j] << endl;
        }
        else {
            while (isPower(i)) {
 
                if ((i) % 2 == 0) {
                    sum += v[i];
 
                    i = i * x - 1;
                    x = 1;
                }
                else {
                    x = x * 2;
                    i = i / 2;
                }
 
 
            }
            sum += v[i];
            x = 1;
            while (isPower(j)) {
 
                if (j % 2 == 0) {
                    sum1 += v[j];
 
                    j = j * x - 1;
                    x = 1;
                }
 
 
                else {
                    x = x * 2;
                    j = j / 2;
                }
 
 
            }
            sum1 += v[j];
 
            cout << (sum1 - sum + v[zz])% 9223372036854775807 << endl;
        }
 
    }
}
Comment

PREVIOUS NEXT
Code Example
Cpp :: fenwick tree 
Cpp :: concatenate 2 vectors in c++ 
Cpp :: function prototype c++ 
Cpp :: delete a head node in link list 
Cpp :: C++ Area and Circumference of a Circle 
Cpp :: size of set c++ 
Cpp :: how to change the type of something in c++ 
Cpp :: math in section latex 
Cpp :: uses of c++ 
Cpp :: accumulate in c++ 
Cpp :: what is ++i and i++ 
Cpp :: how to find maximum value in c++ 
C :: C output color font 
C :: what is meaning of product *= in c 
C :: factorial in c 
C :: c get file size 
C :: react-textfit 
C :: Using PostgreSQL array to store many-to-many relationship using sqlalchemy 
C :: see if two strings are equal in C 
C :: printf signed char 
C :: search array element in c 
C :: c convert integer to string 
C :: tkinter create_line 
C :: check if string in string c 
C :: c language time() function 
C :: strcasecmp c 
C :: c fopen 
C :: c/c++ windows api download file 
C :: server client tcp in C 
C :: c bits 
ADD CONTENT
Topic
Content
Source link
Name
4+3 =