Yet Another Rails Problem

mail@pastecode.io avatar
unknown
python
2 years ago
1.1 kB
2
Indexable
Never
from collections import deque

def another_rail_problem(B):
    A = deque([len(B)+1])
    station = deque([])
    # i = 0
    while(len(B) > 0 or len(station) > 0):
        # i = i + 1
        # print('At round', i)
        if len(B) > 0 and B[-1] == A[0] -1:
            A.appendleft((B.pop()))
        elif len(station) > 0 and station[-1] == A[0] - 1:
            A.appendleft((station.pop()))
        elif len(station) == 0 or B[-1] < station[0]:
            station.appendleft(B.pop())
        else: 
            return 'NO'
        # print('B:', B)
        # print('Station:', station)
        # print('A:', A, '\n')
    return 'YES'

# B = [1, 2, 3, 4, 5]               # YES
# B = [5, 4, 3, 2, 1]               # NO
# B = [3, 4, 1, 2, 5]               # YES
# B = [3, 4, 1, 2, 7, 8, 5, 6]      # YES
# B = [3, 4, 1, 2, 7, 8, 6, 5]      # NO


# print('Original B:', B, '\n')
# print(another_rail_problem(B))

T = int(input())
for _ in range(T):
    n = int(input())
    B = list(map(int, input().split()))
    print(another_rail_problem(B))