Advertisement
dark-Matter

A-C transfer

Sep 17th, 2020
286
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.98 KB | None | 0 0
  1. from bisect import bisect_left, bisect_right
  2. from sys import stdin, stdout, maxsize
  3.  
  4.  
  5. R = lambda : stdin.readline().strip()
  6. RL = lambda f=None: list(map(f, R().split(' '))) if f else list(R().split(' '))
  7.  
  8. output = lambda x: stdout.write(str(x) + '\n')
  9. output_list = lambda x: output(' '.join(map(str, x)))
  10.  
  11. # solution starts from here
  12.  
  13. a = list(R())
  14.  
  15. stack = []
  16. next_smallest = len(a)*[-1]
  17.  
  18. for i in range(len(a)):
  19.     while len(stack) and a[stack[-1]] > a[i]:
  20.         stack.pop(-1)
  21.     if len(stack):
  22.         next_smallest[stack[-1]] = i
  23.     stack.append(i)
  24.  
  25. i =  a.index(min(a))
  26. ans = [a[i]]
  27. stack = a[:i]
  28.  
  29. while i < len(a) and i > -1:
  30.     while len(stack) and next_smallest[i]>-1 and stack[-1] < a[next_smallest[i]]:
  31.         ans.append(stack[-1])
  32.         stack.pop()
  33.     if next_smallest[i] > -1:
  34.         stack += a[i+1:next_smallest[i]]
  35.         ans.append(a[next_smallest[i]])
  36.     i = next_smallest[i]
  37.  
  38. stack.reverse()
  39. ans += stack
  40.  
  41. output(''.join(ans))
  42.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement