[파이썬] 백준 - 19단계 스택
스택 (10828)
import sys
N = int(input())
temp = []
for i in range(N):
s = list(sys.stdin.readline().rstrip().split())
if s[0] == 'push' :
temp.append(s[1])
if temp == [] :
if s[0] == 'size' :
print(0)
elif s[0] == 'pop' :
print(-1)
elif s[0] == 'top' :
print(-1)
elif s[0] == 'empty' :
print(1)
else :
if s[0] == 'size' :
print(len(temp))
elif s[0] == 'pop' :
print(temp[-1])
temp.pop(-1)
elif s[0] == 'top' :
print(temp[-1])
elif s[0] == 'empty' :
print(0)
제로 (10773)
import sys
K = int(input())
temp = []
for i in range(K):
money = int(sys.stdin.readline().rstrip())
if money == 0 :
temp.pop(-1)
else :
temp.append(money)
print(sum(temp))
괄호 (9012)
N = int(input())
for i in range(N):
s = input()
temp = []
for j in range(len(s)):
if temp == []:
if s[j] == '(' :
temp.append(s[j])
else :
temp.append(s[j])
break
else :
if temp[-1] == '(' and s[j] == ')' :
temp.pop(-1)
elif temp[-1] == ')' and s[j] == '(' :
temp.pop(-1)
else :
temp.append(s[j])
if temp == [] :
print('YES')
else :
print('NO')
균형잡힌 세상 (49490)
p_open,p_close = ['(','['],[')',']']
while True :
temp = []
s = input()
if s == '.' :
break
for j in range(len(s)):
if s[j] in p_open+p_close : # 괄호만 진행
if temp == [] : # 비어있을 때 닫는 괄호면 x
if s[j] in p_close :
temp.append(s[j])
break
else :
temp.append(s[j])
else :
if temp[-1] == '(' and s[j] == ')' :
temp.pop(-1)
elif temp[-1] == '[' and s[j] == ']' :
temp.pop(-1)
else :
temp.append(s[j])
if temp == [] :
print('yes')
else :
print('no')
반복문 실행하면서 닫는 괄호 먼저 나왔을 때는 break.
아닌 경우에는 짝 맞을 때 하나씩 제거
스택 수열 (1874)
N = int(input())
goal = []
temp = ''
make = True
for i in range(N): # 목표
a = int(input())
if i == 0 :
goal += list(range(1,a+1))
temp += '+'*goal[-1]
temp += '-'
memory = goal[-1]
goal.pop(-1)
else :
if a < memory : # 메모리보다 작은거
if goal[-1] == a :
temp += '-'
goal.pop(-1)
else :
make = False
break
else : # 메모리보다 큰거 push해주고 마지막 pop
goal += list(range(memory+1,a+1))
temp += '+'*(goal[-1]-memory)
temp += '-'
memory = goal[-1]
goal.pop(-1)
if make == True :
for i in temp :
print(i)
else :
print('NO')
어렵진 않은데 시간 보니까 비효율적으로 짠듯..시간이 sys.stdin.readline()쓰면 1000ms 안쓰면 4000ms
'Algorithm > etc' 카테고리의 다른 글
[파이썬] 백준 1759: 암호만들기 (골드5) (0) | 2023.05.11 |
---|---|
[파이썬] 백준 1411: 비슷한 단어 (실버2) (0) | 2023.05.08 |
[파이썬] 백준 - 15단계 약수,배수와 소수2 (0) | 2023.04.28 |
[파이썬] 백준 - 실랜디 (0) | 2023.04.20 |
[파이썬] 백준 - 18단계 심화2 (0) | 2023.04.19 |
[파이썬] 백준 - 17단계 조합론 (0) | 2023.04.19 |
[파이썬] 백준 - 14단계 집합과 맵 (0) | 2023.04.18 |
댓글