E - 1D puyopuyo Editorial by en_translator
First of all, the final value of \(|A|\) is independent of the order of operations. Thus, we will simulate the operations, imposing an additional constraint: if there are multiple possible operations, we always perform the one that erases the elements positioned earliest.
If you naively simulate this process, the worst time complexity will be \(O(N^2)\), leading to a TLE (Time Limit Exceeded) verdict. How can we speed it up?
Here we can use a data structure called stack. Using stack, we can conduct the simulation as follows:
- Prepare a stack \(Q\).
- For \(i=1,2,\ldots,N\) in order, perform the following:
- Insert \(A_I\) to the end of \(Q\).
- If the last four elements of \(Q\) are all equal, remove the last element of \(A\) four times.
- After the iteration above, the final number of elements in \(A\) is the sought answer.
One can insert an element to, and remove an element from, a stack in \(O(1)\) time, so the problem can be solved in a total of \(O(N)\) time.
The problem can be solved by implementing the algorithm appropriately.
n = int(input())
q = []
for v in list(map(int, input().split())):
q.append(v)
if len(q) >= 4 and q[-1] == q[-2] == q[-3] == q[-4]:
for i in range(4):
q.pop()
print(len(q))
posted:
last update: