Psychos in a Line (Codeforces 319B)
Tags: Implement, data structures

There are n psychos standing in a line. Each psycho is assigned a unique integer from 1 to n. At each step every psycho who has an id greater than the psycho to his right (if exists) kills his right neighbor in the line. Note that a psycho might kill and get killed at the same step. You're given the initial arrangement of the psychos in the line. Calculate how many steps are needed to the moment of time such, that nobody kills his neighbor after that moment. Look notes to understand the statement more precise.

Input: The first line of input contains integer n denoting the number of psychos, (1 ≤ n ≤ 105). In the second line there will be a list of n space separated distinct integers each in range 1 to n, inclusive — ids of the psychos in the line from left to right.

Output: Print the number of steps, so that the line remains the same afterward.

Note: In the first sample line of the psychos transforms as follows: [10 9 7 8 6 5 3 4 2 1]  →  [10 8 4]  →  [10]. So, there are two steps.

Sample Inputs:
10
10 9 7 8 6 5 3 4 2 1

6
1 2 3 4 5 6

Sample Outputs:
2

0

Solution (Python):
def Psycho():
    cantidad = int(input())
    lista = list(map(int, input().split()))
    lista = lista[::-1]
    result = 0
    queue = []
    for psycho in lista:
        aux_porElem = 0
        while len(queue) > 0 and queue[-1][0] < psycho:
            aux_porElem = max((aux_porElem + 1, queue[-1][1]))
            queue.pop()
        queue.append((psycho, aux_porElem))
        if aux_porElem > result:
            result = aux_porElem
    return result
print(Psycho())

Solution (Python):
inf = 10000000

def solve(lst):
    values = [0]
    for i in range(len(lst)):
        values.append(lst[i])
    n = len(lst)
    life = [0] * (n + 1)
    life[0] = inf
    killers = [0]
    for i in range(1, n + 1):
        life[i] = 1
        while len(killers) > 0 and values[i] > values[killers[-1]]:
            life[i] = max(life[i], life[killers[-1]] + 1)
            killers.pop()
        killers.append(i)
    ans = 0
    for i in range(1, n + 1):
        if life[i] < inf:
            ans = max(ans, life[i])
    return ans
n = int(input())
lst = list(map(int, input().strip().split()))[:n]
print(solve(lst))

Solution (Python):
(n, t) = (int(input()), list(map(int, input().split())))
(p, s, r) = ([0] * n, [0] * n, t[0])
for i in range(n - 1):
    j = i + 1
    x = t[j]
    if x > r:
        r = x
    else:
        while t[i] < x:
            (s[j], i) = (max(s[j], s[i]), p[i])
        p[j] = i
        s[j] += 1
print(max(s))