## Editorial for DMOPC '20 Contest 6 P2 - Interpretive Art

**only**when stuck, and

**not to copy-paste code from it**. Please be respectful to the problem author and editorialist.

**Submitting an official solution before solving the problem yourself is a bannable offence.**

Author:

The solution relies on 2 key observations.

- When we perform a brush stroke on a range, we can consider it as moving all of the s to the left of the range and all of the s to the right. This also means that s can only move to the left, whereas s can only move to the right.
- If we number the s in (first , second , third , etc.), then their relative order never changes after any brush stroke.

The key idea now is that we must match the -th in with the -th in . First, let us check for impossibility. There are 2 cases where it is impossible to turn into .

- If the number of s in is not equal to the number of s in .
- If the -th in is to the left of the -th in (since s can only move to the left, these will never be matched).

All other cases are possible; we can simply spend brush stroke for each pair of s in and and match them into the correct positions. We now provide an algorithm that uses the minimum possible number of brush strokes, assuming that it is possible to turn into :

Consider the first "chunk" of s in , consisting of consecutive s. We can simply find the position of the -th in , and use a brush stroke from index to the position of the -th in (unless the position of the -th in is the same as the position of the -th in , in which case this chunk is already matched). This will match the chunk of s, as well as the following chunk of s; if it didn't, then there would be a in where there should be a , but since s only move to the left and no more s are needed on the left side, this contradicts the assumption of possibility. Also, note that any other combination of strokes that matches the first chunk of s in will result in the exact same arrays and , so is definitely the optimal number of brush strokes if any are needed. Then, since the first chunk of s and s are matched, we can remove these chunks and restart the algorithm on the shortened arrays, where the proof of correctness is propagated.

That may sound like a mouthful, but it is really only there for logical rigour and a proof of optimality. The TL;DR is to just match every chunk of s in with the correct number of s in from left to right.

#### Subtask 1

Simply simulating the algorithm above yields an or solution, both of which are sufficient to pass this subtask.

**Time Complexity:** or

#### Subtask 2

A slightly optimized approach is required for this subtask. For example, one may store the index of the -th in for all , and only consider using a brush stroke when encountering an index such that and . There are, of course, a ton of other possible approaches as well.

**Time Complexity:**

## Comments