728x90
2493. 탑
import sys
n = int(input())
towers = list(map(int, sys.stdin.readline().split()))
receiver = [0]
while towers != []:
if receiver == [0]:
print(0)
receiver.append(towers.pop(0))
continue
elif towers[0] <= receiver[-1]:
print(len(receiver)-1)
receiver.append(towers.pop(0))
continue
else:
i = len(receiver)
while i >= 0:
i -= 1
if towers[0] <= receiver[i]:
print(i)
receiver.append(towers.pop(0))
break
if i == 0:
print(0)
receiver.append(towers.pop(0))
break
continue
스택에 자신감이 붙어 당차게 골드에 도전했지만 시간초과로 탈탈 털리고... receiver의 index값을 저장할 방법을 생각 못해서 계속 O(N*2)인 방법에서 헤매고 있었다.
import sys
n = int(input())
towers = list(map(int, sys.stdin.readline().split()))
receiver = [0]*n
stack = []
for i in range(n):
if stack:
while True:
if towers[i] <= stack[-1][0]:
receiver[i] = stack[-1][1]+1
stack.append([towers[i], i])
break
else:
stack.pop()
if stack == []:
stack.append([towers[i], i])
break
else:
stack.append([towers[i], i])
for i in receiver:
print(i, end = ' ')
결국 컨닝을 좀..이 아니라 많이 했다. 애초에 스택에 index값을 포함해서 넣으면 되는 것이었다. 그래도 들여쓰기 헷갈리는 코드 꼭꼭 씹어먹었으니 일단 답에 거의 근접했다는 것에 위안을 얻는다. 겁내지 말고 답을 좀 찾아보자!!
728x90
'알고리즘 > 백준' 카테고리의 다른 글
[백준]230203 문제풀이 (0) | 2023.02.04 |
---|---|
[백준]230202 문제풀이 (2) | 2023.02.02 |
[백준]230128-30 문제풀이 (0) | 2023.01.30 |
[백준]230127 문제풀이 (0) | 2023.01.30 |
[백준]230126 문제풀이 (0) | 2023.01.26 |
댓글