Editorial for LCC/Moose '19 Contest 1 J5 - Om and uwu


Remember to use this editorial 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: Riolku

This problem uses a technique commonly referred to as "two-pointer". The idea is that if you have a subarray  [L, R] that contains the given subsequence, then  [A, B] is also valid for all  A \le L and  R \le B .

There are two approaches to this problem: forward, or (you guessed it) backward.

Forward

In this approach, you iterate  L and try to keep track of the minimum possible  R . To do this, keep 5 pointers, one to the first u (call it u1), one to the first w (call it w1), one to the second u and so on.

Now, as you move forward in the string, keep track of these pointers. If  L > u1 , you increment u1 until it reaches another u. If  w1 < u1 , you now need to move  w1 in order to form a valid subsequence. Keep moving your 5 pointers like this. At the end, u3 is your  R value, since it points to the last u in the first possible subsequence starting at  L .

Now, you add  N - u3 (0-indexed) to your total, since any  A \ge R will suffice. This way, you process every  L and count all possible corresponding  R s.

Since each pointer will visit each index at most once (which is crucial!), the solution is  \mathcal O(N) .

Backward

In this approach, you still process all L, but you do so backwards. The idea is that you still maintain 5 pointers, but each pointer refers to the first  R where that subsequence exists. For example, for the first pointer, it is the first  R where the subsequence u exists in the range  [L, R] . Each time you see a u or a w, you can use previous pointers to update your pointers and decrease  R .

Lets call our pointers u1, w1, u2, w2, u3 that represent the subsequences u wu uwu wuwu uwuwu respectively. Each time you see a u at index i, do the following update:

u3, u2, u1 = w2, w, i

This is because the first subsequence of u is at i, as far as you know right now. Similarly, since w2 represent a subsequence wuwu, if you have a u, you can form uwuwu. The update for w is similar.

Again, you can add  N - u3 each time to your total.


Comments

There are no comments at the moment.