import sys
n = int(input())
a = list(map(int,sys.stdin.readline().split()))
i = 0
stack = []
next = [-1] * n
while True:
if stack and stack[0] == i:
break
while stack and a[stack[-1]] < a[i]:
popped = stack.pop()
next[popped] = i
stack.append(i)
i += 1
i %= n
# print(a)
# print(next)
back = {}
q, nq = [], []
for i in range(n):
if next[i] == -1:
q.append(i)
else:
if next[i] in back:
back[next[i]].append(i)
else:
back[next[i]] = [i]
ans = 0
while q:
ans += 1
for i in q:
if i in back:
nq.extend(back[i])
q, nq = nq, []
print(ans)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | import sys n = int(input()) a = list(map(int,sys.stdin.readline().split())) i = 0 stack = [] next = [-1] * n while True: if stack and stack[0] == i: break while stack and a[stack[-1]] < a[i]: popped = stack.pop() next[popped] = i stack.append(i) i += 1 i %= n # print(a) # print(next) back = {} q, nq = [], [] for i in range(n): if next[i] == -1: q.append(i) else: if next[i] in back: back[next[i]].append(i) else: back[next[i]] = [i] ans = 0 while q: ans += 1 for i in q: if i in back: nq.extend(back[i]) q, nq = nq, [] print(ans) |
English