/* A recursive function to get the sum of values in given range of the array. The following are parameters for this function. st --> Polong long inter to segment tree index --> 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[index] qs & qe --> Starting and ending indexes of query range */ unsigned long long int getSumUtil(long long int *st, long long int ss, long long int se, long long int qs, long long int qe, long long int index) { // 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[index]; // 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 unsigned long long int mid = getMid(ss, se); return getSumUtil(st, ss, mid, qs, qe, 2*index+1) + getSumUtil(st, mid+1, se, qs, qe, 2*index+2); }
/* A recursive function to get the sum of values in 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); }
// Return sum of elements in range from index qs (quey start) to // qe (query end). It mainly uses getSumUtil() lint getSum(lint *st, lint n, lint qs, lint qe) { // Check for erroneous input values if (qs < 0 || qe > n-1 || qs > qe) { return 0; } return getSumUtil(st, 0, n-1, qs, qe, 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) { printf("Invalid Input"); return -1; } return getSumUtil(st, 0, n-1, qs, qe, 0); }
// Return sum of elements in range from index qs (quey start) to // qe (query end). It mainly uses getSumUtil() unsigned long long int getSum(long long int *st, long long int n, long long int qs, long long int qe) { // Check for erroneous input values return getSumUtil(st, 0, n-1, qs, qe, 0); }