segment tree complexity

// C++ program to show segment tree operations like construction, query 
// and update 
#include <bits/stdc++.h> 
using namespace std; 

// A utility function to get the middle index from corner indexes. 
int getMid(int s, int e) { return s + (e -s)/2; } 

/* A recursive function to get the sum of values in the given range 
	of the array. The following are parameters for this function. 

	st --> Pointer to segment tree 
	si --> Index of current node in the segment tree. Initially 
			0 is passed as root is always at index 0 
	ss & se --> Starting and ending indexes of the segment represented 
				by current node, i.e., st[si] 
	qs & qe --> Starting and ending indexes of query range */
int getSumUtil(int *st, int ss, int se, int qs, int qe, int si) 
{ 
	// If segment of this node is a part of given range, then return 
	// the sum of the segment 
	if (qs <= ss && qe >= se) 
		return st[si]; 

	// If segment of this node is outside the given range 
	if (se < qs || ss > qe) 
		return 0; 

	// If a part of this segment overlaps with the given range 
	int mid = getMid(ss, se); 
	return getSumUtil(st, ss, mid, qs, qe, 2*si+1) + 
		getSumUtil(st, mid+1, se, qs, qe, 2*si+2); 
} 

/* A recursive function to update the nodes which have the given 
index in their range. The following are parameters 
	st, si, ss and se are same as getSumUtil() 
	i --> index of the element to be updated. This index is 
			in the input array. 
diff --> Value to be added to all nodes which have i in range */
void updateValueUtil(int *st, int ss, int se, int i, int diff, int si) 
{ 
	// Base Case: If the input index lies outside the range of 
	// this segment 
	if (i < ss || i > se) 
		return; 

	// If the input index is in range of this node, then update 
	// the value of the node and its children 
	st[si] = st[si] + diff; 
	if (se != ss) 
	{ 
		int mid = getMid(ss, se); 
		updateValueUtil(st, ss, mid, i, diff, 2*si + 1); 
		updateValueUtil(st, mid+1, se, i, diff, 2*si + 2); 
	} 
} 

// The function to update a value in input array and segment tree. 
// It uses updateValueUtil() to update the value in segment tree 
void updateValue(int arr[], int *st, int n, int i, int new_val) 
{ 
	// Check for erroneous input index 
	if (i < 0 || i > n-1) 
	{ 
		cout<<"Invalid Input"; 
		return; 
	} 

	// Get the difference between new value and old value 
	int diff = new_val - arr[i]; 

	// Update the value in array 
	arr[i] = new_val; 

	// Update the values of nodes in segment tree 
	updateValueUtil(st, 0, n-1, i, diff, 0); 
} 

// Return sum of elements in range from index qs (quey start) 
// to qe (query end). It mainly uses getSumUtil() 
int getSum(int *st, int n, int qs, int qe) 
{ 
	// Check for erroneous input values 
	if (qs < 0 || qe > n-1 || qs > qe) 
	{ 
		cout<<"Invalid Input"; 
		return -1; 
	} 

	return getSumUtil(st, 0, n-1, qs, qe, 0); 
} 

// A recursive function that constructs Segment Tree for array[ss..se]. 
// si is index of current node in segment tree st 
int constructSTUtil(int arr[], int ss, int se, int *st, int si) 
{ 
	// If there is one element in array, store it in current node of 
	// segment tree and return 
	if (ss == se) 
	{ 
		st[si] = arr[ss]; 
		return arr[ss]; 
	} 

	// If there are more than one elements, then recur for left and 
	// right subtrees and store the sum of values in this node 
	int mid = getMid(ss, se); 
	st[si] = constructSTUtil(arr, ss, mid, st, si*2+1) + 
			constructSTUtil(arr, mid+1, se, st, si*2+2); 
	return st[si]; 
} 

/* Function to construct segment tree from given array. This function 
allocates memory for segment tree and calls constructSTUtil() to 
fill the allocated memory */
int *constructST(int arr[], int n) 
{ 
	// Allocate memory for the segment tree 

	//Height of segment tree 
	int x = (int)(ceil(log2(n))); 

	//Maximum size of segment tree 
	int max_size = 2*(int)pow(2, x) - 1; 

	// Allocate memory 
	int *st = new int[max_size]; 

	// Fill the allocated memory st 
	constructSTUtil(arr, 0, n-1, st, 0); 

	// Return the constructed segment tree 
	return st; 
} 

// Driver program to test above functions 
int main() 
{ 
	int arr[] = {1, 3, 5, 7, 9, 11}; 
	int n = sizeof(arr)/sizeof(arr[0]); 

	// Build segment tree from given array 
	int *st = constructST(arr, n); 

	// Print sum of values in array from index 1 to 3 
	cout<<"Sum of values in given range = "<<getSum(st, n, 1, 3)<<endl; 

	// Update: set arr[1] = 10 and update corresponding 
	// segment tree nodes 
	updateValue(arr, st, n, 1, 10); 

	// Find sum after the value is updated 
	cout<<"Updated sum of values in given range = "
			<<getSum(st, n, 1, 3)<<endl; 
	return 0; 
} 
//This code is contributed by rathbhupendra 

4.5
6
Awgiedawgie 440215 points

                                    class SegmentTree{
public:
    vector&lt;int&gt; segv;
    int n;
    SegmentTree(vector&lt;int&gt; &amp;nums) {
        if (!nums.size()) return ;
        segv.assign(nums.size() * 4, 0);
        n = nums.size();
        build(nums, 1, 0, n - 1); 
    }
    void build(vector&lt;int&gt; &amp;nums, int v, int l, int r) {
        if (l == r) segv[v] = nums[l];
        else {
            int mid = l + (r - l) / 2;
            build(nums, v * 2, l, mid);
            build(nums, v * 2 + 1, mid + 1, r);
            segv[v] = segv[v * 2] + segv[v * 2 + 1]; 
        }
    }
    int sumRange(int v, int l, int r, int a, int b) {
        if (a &gt; b) return 0;
        if (l == a &amp;&amp; r == b) return segv[v];
        int mid = l + (r - l) / 2;
        return sumRange(v * 2, l, mid, a, min(mid, b))
            + sumRange(v * 2 + 1, mid + 1, r, max(mid + 1, a), b);
    }
    void update(int v, int l, int r, int pos, int val) {
        if (l == r) segv[v] = val;
        else {
            int mid = l + (r - l) / 2;
            if (pos &lt;= mid) update(v * 2, l, mid, pos, val);
            else update(v * 2 + 1, mid + 1, r, pos, val);
            segv[v] = segv[v * 2] + segv[v * 2 + 1];
        }
    }
    int sumRange(int a, int b) {
        return sumRange(1, 0, n - 1, a, b);
    }
    void update(int pos, int val) {
        update(1, 0, n - 1, pos, val);
    }
};

4.5 (6 Votes)
0
5
1
Awgiedawgie 440215 points

                                    void build(int node, int start, int end)
{
    if(start == end)
    {
        // Leaf node will have a single element
        tree[node] = A[start];
    }
    else
    {
        int mid = (start + end) / 2;
        // Recurse on the left child
        build(2*node, start, mid);
        // Recurse on the right child
        build(2*node+1, mid+1, end);
        // Internal node will have the sum of both of its children
        tree[node] = tree[2*node] + tree[2*node+1];
    }
}

5 (1 Votes)
0
Are there any code examples left?
Create a Free Account
Unlock the power of data and AI by diving into Python, ChatGPT, SQL, Power BI, and beyond.
Sign up
Develop soft skills on BrainApps
Complete the IQ Test
Relative searches
segment trees detailed explanation segment treeproblems all concept in segment tree? problem on segment tree segment tree on trees what is segment tree in data structure segment trees geeks segmentation tree algorithm segment tree in cpp segmentation tree segment trees explained what is a segment tree tree segmentation what are segment trees used for binary segment tree segment tree implementation' segment tree variatin segment tree questions segment tree geeks whata are segment trees where is segment trees used what is segment tree in c++ segment tree implementation time how to implement segment tree is binary tree a segment tree what are segment trees why is segment tree used why is segment trees used for Segment Tree? what is segment trees segment trees on trees segment trees implementation segment trees cpp segment tree algorithm segmented binary tree Left part of segment + Right part of segment = Whole segment building segment tree in tree segment trees stl segment treew segment tree tutorial point segment tree sorted segment tree on tree segment tree problemds how much time to learn segement tree in competetive programming queries on trees complete segmented tree for subset of array make queries on segment gfg segment tree segment tree implementation C how to find the ith element in segment ttee segment tree codefo range query segment tree practce implementation of segment tree segment tree in c++ using recursion segment tree in c++ using an array to represent a segment tree segment tree storage size segment summary c++ Segment Tree with Lazy Update segment tree problems segment tree time complexity segment tree for prime truple segment tree structure in c++ segment tree best implementation in structure segment treee time complexity of segment tree Solution KQUERY with persistent segmet tree segment tree segment tree segment sum complexity segment tree range sum segment tree cp sgement tree code segmenr tree range query segment tree execution online merge sort tree cp algorithm Segment tree query type explaination time complexity of segment tree c++ understand segment tree in depth complexity of building a segment tree segment tree cost of erase segment tree complexity Addition to Segment segment tree min segment tree implementation segment tree update segment tree implementation codencode cp-algorithms segment tree E. Copying Data using segment tree inbuilt segment tree c++ application of segment trees cp algorithm segment tree traverse segment trees SEGMENT TREE} segmented tree an introduction to segment tree in under 1 minute seqmented binary tree segment tree time complexity list segment tree defnition time complexity segment tree deletion time complexity segment tree cp python hackerearth segment tree codencode segment tree segment tree implimentation segment tree update implimentation segment trees hackerearth What are systematic ways to prepare for segment trees? Addition and Minimum segment tree Addition to Segment code segment tree limitations is a segment tree perfectly balanced segment tree sum of given range algorithm segment tree how segment tree A. Segment Tree for the Sum segment tree struct code segment tree struct tourist how to learn segment tree segment tree tutorial competitive programming segment tree c# custom Binary segment tree graph node segment tree details segment tree erase complexity segmend tree c++ segment tree cp algorithm segment tree tree implementation range max segment tree cp algorithm function to convert a segment tree to a vector segment tree complexity segment reee when is segment tree used sesgment tree segment ree segment tree implementation c++ tree path queries using segment tree how to find su of all child node to root node using segment tree get root inside the segment tree tranform segment tree in persistent segment tree costruction segment tree timecomplexity segment tree of segment tree line segment tree segement tree segement tree cp algorithms segment trees coding freak Segment Trees comes under which Topic in Data Structures segment tree data structure segment trees cp algorithms lazy propagation cp algorithms segment tree sum of given range sum of subarray length segment tree struct segment tree add nodes compress all sub segments cpp segment tree alternate names what is segmentat tree seggment tree segment tree implementation tree like segment tree trees similar to segment tree segment array c++ segment tree range sum query second thread segment tree implementation segment array left child segment array segment tree class class of segment tree for rmq with update and rmq how to calculate sum in a segment tree on a basis of condition what is segment tree segemnt tree min number from l to r segment tree segment trees segment tree gfg segmemnt tree cp algorithms segment tree segment tree cp algorithms first element at least x segment tree segment tree range update and range query in lazy segment tree as a BItwise and and Bitwise or Segment Tree point update rage sum c++ segment tree segment tree c++ Array Queries segment tree how to solve add query in log n time total sum of array segment tree search python easy segment tree implementation in c++ segment tree cpp stl segmental tree implemnetation in c++ segment tree query not including zero index segment tree query construct segment tree from array what is the value at position k? in segment tree in c++ range sum query segment tree compress the given borders of segments c++ how to build a segment tree in array segment tree cpp segment tree which number is repeated in c++ boolean array segment tree geeks segment tree code segment tree query time segment treee cpp segment tree implementation using c++ segment tree c++ implementation update query in segment tree segment tree sum query SAMPLE CODE FOR SEGMENT TREE segmented trees
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source