Subtask 1:
We will solve subtask 1 with bruteforce. So, for all index i in the sub-segment [L - R] we will add |X - Ai| to the result.
Time Complexity: For per test case, time complexity is O(N × Q).
Subtask 2:
In subtask 2, there will be at most 10 distinct values. We will work with these values. We will declare a vector for every distinct value. In the vector we will store the index in which index the value is exist. For every query we will count the number of index in the sub-segment [L - R] in a vector. We can find it easily with binary search. If this value is val and it's counter is cnt, we will add |X - val| × cnt to the result. We will do this for every vector. The values are so big, so we will do the work with the compress value.
Time Complexity: For per test case, time complexity is O(Q × D × Log2N), where D = Number of distinct values.
Subtask 3:
To solve subtask 3, we have to use data-structure. We will solve the problem using the segment tree. At first we will build a segment tree. In every node of the segment tree there are two vectors. In the first vector we will store the values of the array A sorted in ascending order in a certain range (current range in the segment tree). It is also called "Merge sort tree".
Now, we will see how can we get the result from this tree. For every query, we will travers the segment tree. We will start traversing from the root node, and we will go down with the child node. If a range of any node is inside the query range, we will work with this node. We will find the number of value which is smaller than X and the numer of value which is bigger than X in the vector in which we have stored the values in sorted order. As the values are sorted, we can find it with binary search. Then we will add |Ps - X × S| + |Pb - X × B| to the result and return from this node.
Here,
S = Number of values smaller than X.
B = Number of values bigger than X.
Ps = Summation of values smaller than X.
Pb = Summation of values bigger than X.

We will find the summation of smaller and bigger values than X from the prefix sum.

Time Complexity: For per test case, time complexity is O(N × Log2N + Q × (Log2N)2).

Statistics

48% Solution Ratio
prodip_bsmrstuEarliest, Aug '20
EgorKulikovFastest, 0.3s
user.536969Lightest, 9.2 MB
MursaleenShortest, 1682B
Toph uses cookies. By continuing you agree to our Cookie Policy.