Problem author: | Maryan Shyika |
Prepared by: | Maryan Shyika |
Tutorial: | Maryan Shyika |
Main Idea
Consider two consecutive occurrences of the same value at positions and , that is,
Initially, every element with value can be considered to require a separate operation. However, sometimes two consecutive occurrences of can be zeroed within the same sequence of operations, which means that the second occurrence does not increase the answer.
This is possible if and only if for every position such that i<k<j, the following two conditions hold:
a_k>x;
a_k\le R.
The first condition means that there is no element between the two equal values that becomes zero earlier than or at the same time as them and prevents us from merging these two occurrences.
The second condition means that all elements between them are allowed to be changed in the current query. Since x\in[L,R] and all intermediate values are strictly greater than , the lower bound is satisfied automatically. Therefore, it is enough to check only the upper bound .
Let cnt_x be the number of elements in the array equal to . Initially, set
The value res_x represents the number of operations contributed to the answer by elements with value .
Whenever two consecutive occurrences of can be merged, we decrease res_x by .
First Condition
We process the array from left to right and maintain pos_x — the last position where the value occurred.
Suppose the current position is , a_j=x, and the previous occurrence of is at position
We need to check that
The minimum on a segment can be found using a segment tree.
It is important to query exactly the segment
without including positions and themselves, since both contain the value .
If i+1>j-1, meaning that the two equal elements are adjacent, this condition is satisfied automatically.
If there is no previous occurrence of , then there is nothing to merge the current element with.
Second Condition
For every pair of consecutive occurrences of that passed the first check, compute
Such a pair can be merged in a query if and only if
Therefore, for every valid pair we create an event
This event means that for every query with R\ge mx, we may decrease
by one.
Sort all events by , and sort all queries by their right border .
We process queries in increasing order of . Before answering the current query, activate all events for which
When activating an event , perform
Answering a Query
For a query , we are interested only in the initial values that belong to this interval.
Therefore, the answer is
To maintain the array , we can use a Fenwick tree or a segment tree.
Initially, we store cnt_x at position . When an event is activated, we perform a point update by , and for each query we compute the sum on the segment .
Thus, all queries can be processed offline.
The overall time complexity is O((n+q)\log n).
The memory complexity is O(n+q).