Editorial for LCC/Moose '19 Contest 1 J5 - Om and uwu
Submitting an official solution before solving the problem yourself is a bannable offence.
Author:
This problem uses a technique commonly referred to as "two-pointer". The idea is that if you have a subarray that contains the given subsequence, then is also valid for all and .
There are two approaches to this problem: forward, or (you guessed it) backward.
Forward
In this approach, you iterate and try to keep track of the minimum possible . 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 , you increment u1
until it reaches another u
. If , you now need to move in order to form a valid subsequence. Keep moving your 5 pointers like this. At the end, u3
is your value, since it points to the last u
in the first possible subsequence starting at .
Now, you add (0-indexed) to your total, since any will suffice. This way, you process every and count all possible corresponding s.
Since each pointer will visit each index at most once (which is crucial!), the solution is .
Backward
In this approach, you still process all , but you do so backwards. The idea is that you still maintain 5 pointers, but each pointer refers to the first where that subsequence exists. For example, for the first pointer, it is the first where the subsequence u
exists in the range . Each time you see a u
or a w
, you can use previous pointers to update your pointers and decrease .
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 each time to your total.
Comments