We use a segment tree in which each vertex stores not a single number but an array. Such a structure is called a merge sort tree. The vertex corresponding to the fundamental segment stores the numbers a_i, \ldots, a_j sorted in ascending order.
Construction. The array of a leaf consists of a single element. The array of an internal vertex is obtained by merging the sorted arrays of its children — just as in a step of merge sort. At each level of the tree, the total length of the arrays equals , and there are O(\log n) levels, so the construction takes O(n \log n) time and the same amount of memory.
Answering a query. To find the number of elements in the segment [l; r] that are less than , we split this segment into fundamental segments of the tree, as in an ordinary segment tree query. Since the array of each vertex is sorted, the number of its elements less than equals the position of the first element not less than — we find it using binary search. The answer to the query is the sum of the found counts.
The segment [l; r] is split into at most O(\log n) fundamental segments, and the binary search in each of them takes O(\log n). Therefore, one query is processed in O(\log^2 n), and all queries in O(q \log^2 n).
Example
For example, for the query (2, 6, 4) the segment is split into three fundamental segments: , and . Their sorted arrays are , and . The binary search in each of them finds one number less than , so the answer is 1 + 1 + 1 = 3.
Similarly, for the query (1, 8, 5) the segment coincides with the root of the tree, and the array \{1, 2, 3, 3, 4, 5, 5, 10\} contains exactly numbers less than . For the query (1, 4, 3) we take the vertex with the array \{1, 2, 3, 4\} — the answer is . For the query (5, 8, 9) we take the vertex with the array \{3, 5, 5, 10\} — the answer is .
Algorithm Implementation
Declare the segment tree . Each of its vertices stores the sorted array of numbers of the corresponding segment.
vector<vector<int> > SegTree;The input array is stored in .
vector<int> a;The function BuildTree builds the segment tree from the array . Vertex corresponds to the segment [\mathit{lpos}; \mathit{rpos}]. A leaf stores the single element . For an internal vertex, we first build both children and then merge their sorted arrays with the function merge in time linear in the length of the segment.
void BuildTree(int v, int lpos, int rpos)
{
if (lpos == rpos)
SegTree[v].push_back(a[lpos]);
else
{
int mid = (lpos + rpos) / 2;
BuildTree(2*v, lpos, mid);
BuildTree(2*v+1, mid+1, rpos);
SegTree[v].resize(rpos - lpos + 1);
merge(SegTree[2*v].begin(), SegTree[2*v].end(),
SegTree[2*v+1].begin(), SegTree[2*v+1].end(),
SegTree[v].begin());
}
}The function Query returns the number of elements in the segment [\mathit{left}; \mathit{right}] that are less than . Vertex corresponds to the segment [\mathit{lpos}; \mathit{rpos}]. If the query segment is empty, return . If the query segment coincides with the segment of the vertex, the answer is given by the function lower_bound: it returns the position of the first element not less than in the sorted array , and all elements to the left of this position are less than . Otherwise, split the query into two parts and recursively descend into both children.
int Query(int v, int lpos, int rpos, int left, int right, int x)
{
if (left > right) return 0;
if ((lpos == left) && (rpos == right))
return lower_bound(SegTree[v].begin(), SegTree[v].end(), x) -
SegTree[v].begin();
int mid = (lpos + rpos) / 2;
return Query(2*v, lpos, mid, left, min(mid, right), x) +
Query(2*v+1, mid+1, rpos, max(left, mid+1), right, x);
}The main part of the program. Read the input array. The elements are stored in a[1], \ldots, a[n], numbered from one.
scanf("%d",&n);
a.resize(n + 1);for(i = 1; i <= n; i++)
scanf("%d",&a[i]);Build the segment tree from the array . For a tree with leaves, vertices are enough.
SegTree.resize(4*n);
BuildTree(1,1,n);Process the queries one by one. For each query, print the number of elements in the segment [l; r] that are less than .
scanf("%d",&q);
for(i = 0; i < q; i++)
{
scanf("%d %d %d",&l,&r,&x);
printf("%d\n",Query(1,1,n,l,r,x));
}Algorithm Implementation — SQRT decomposition
Let us consider another solution — square root decomposition. Split the array into blocks of length \mathit{len} \approx \sqrt{n}; there will be at most blocks. For each block , store its elements in and sort them. The precomputation takes O(n \log n).
Processing a query (l, r, x) depends on the location of its boundaries:
if and lie in the same block (\mathit{c\_l} = \mathit{c\_r}), we simply iterate over the elements a[l], \ldots, a[r];
otherwise, we process by brute force the "tail" of the left block from to its end and the "head" of the right block from its beginning to , and for each full block between them we find the number of elements less than by binary search lower_bound in the sorted array .
The incomplete blocks contain at most 2 \cdot \mathit{len} elements, and there are at most full blocks, so a query is processed in O(\sqrt{n} \log n). In this implementation indices are numbered from zero, so after reading a query we decrease and by .
For example, for the query (1, 8, 5) with n = 8 we get \mathit{len} = 3 and three blocks: \{1, 3, 2\}, \{4, 3, 10\}, . Blocks and are processed by brute force, and for the full block we perform binary search in b[1] = \{3, 4, 10\}:
#include <cstdio>
#include <vector>
#include <set>
#include <algorithm>
#include <cmath>
using namespace std;
vector<int> a;
vector<vector<int> > b;
int i, n, q, len, blocks, l, r, x;
int main()
{
scanf("%d", &n);
a.resize(n);
len = sqrt(n) + 1;
blocks = ceil((double)n / len);
b.resize(len);
for (i = 0;i < n; i++)
{
scanf("%d", &a[i]);
b[i / len].push_back(a[i]);
}
scanf("%d", &q);
for (i = 0;i < blocks; i++)
sort(b[i].begin(), b[i].end());
while (q--)
{
scanf("%d %d %d", &l, &r, &x);
l--; r--;
int res = 0;
int c_l = l / len, c_r = r / len;
if (c_l == c_r)
{
for (i = l; i <= r; i++)
if (a[i] < x) res++;
}
else
{
for (i = l; i <= (c_l + 1)*len - 1; i++)
if (a[i] < x) res++;
for (i = c_l + 1; i <= c_r - 1; i++)
res += lower_bound(b[i].begin(), b[i].end(), x) - b[i].begin();
for (i = c_r * len; i <= r; i++)
if (a[i] < x) res++;
}
printf("%d\n", res);
}
return 0;
}