inline void updateValueUtil(int ll, int lr, int at, int add, int root) { if (at < ll || at > lr) return; sum_tree[root] += add; if (ll == lr) return; int lm = (ll + lr) / 2; updateValueUtil(ll, lm, at, add, 2 * root + 1); updateValueUtil(lm + 1, lr, at, add, 2 * root + 2); }
/* A recursive function to update the nodes which have the given index in their range. The following are parameters st, index, ss and se are same as getSumUtil() i --> index of the element to be updated. This index is in input array. diff --> Value to be added to all nodes which have i in range */ void updateValueUtil(long long int *st, long long int ss, long long int se, long long int i, long long int diff, long long int index) { // 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[index] = st[index] + diff; if (se != ss) { long long int mid = getMid(ss, se); updateValueUtil(st, ss, mid, i, diff, 2*index + 1); updateValueUtil(st, mid+1, se, i, diff, 2*index + 2); } }
inline void updateValue(int n, int at, int val) { if (at < 0 || at > n - 1) { printf("Invalid input\n"); return; } int d = val - arr[at]; arr[at] += val; updateValueUtil(0, n - 1, at, d, 0); }
// 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) { 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); }
// The function to update a value in input array and segment tree. // It uses updateValueUtil() to update the value in segment tree void updateValue(long long int arr[], long long int *st, long long int n, long long int i, long long int new_val) { // Check for erroneous input index if (i < 0 || i > n-1) { //printf("Invalid Input"); return; } // Get the difference between new value and old value long long int diff = new_val; // Update the value in array arr[i] = arr[i] + new_val; // Update the values of nodes in segment tree updateValueUtil(st, 0, n-1, i, diff, 0); }