Official

D - Division into 3 Editorial by evima


First, let’s consider the case with one query.

Suppose the input is B=(B1,,BN)B=(B_1,\cdots,B_N). First, let Bm=max(B)B_m=\max(B). When decomposing BB into XYZXYZ, we will consider the cases based on where BmB_m is included among X,Y,ZX, Y, Z.

First, the case where BmB_m is included in YY is simple. Since max(Y)\max(Y) is determined to be BmB_m, there is no harm in making YY larger. Therefore, we only need to consider the pattern X=(B1),Y=(B2,,BN1),Z=(BN)X=(B_1), Y=(B_2,\cdots,B_{N-1}), Z=(B_N).

Next, let’s consider the case where BmB_m is included in XX. By the same reasoning as before, YY can be assumed to contain only one element. By trying all possible positions for YY, we can calculate the answer.

The case where BmB_m is included in ZZ is similar to the case for XX. By reversing the sequence, we can solve it with exactly the same code.

Next, let’s consider answering multiple queries.

The case where BmB_m is included in YY is still simple and can be handled with a simple RMQ.

There are two main approaches to handle the case where BmB_m is included in XX.

The first approach is to manage max(Z)\max(Z) for each YY. We will process the queries in ascending order of RiR_i. As RiR_i increases, max(Z)\max(Z) for each YY will also increase. This increase can be represented by range addition, so we can solve it using a segment tree with range addition and range minimum query.

The second approach is to manage YY for each max(Z)\max(Z). Similar to the first approach, we process the queries in ascending order of RiR_i. We manage the possible values of max(Z)\max(Z) with a stack and also manage the possible minimum values for YY. This can be implemented with a simple segment tree for range minimum query.

Using either approach, the time complexity will be O((N+Q)logN)O((N+Q) \log N).

Sample Solution for Approach 1 (C++)

Sample Solution for Approach 2 (C++)

posted:
last update:



2025-03-21 (Fri)
04:10:03 +00:00