10845. 큐
문제 링크
📖 문제 설명
- 큐에 대해서 알아본다.
- push, pop, size, empty, front, back을 입력하면 각각에 맞는 연산을 해주는 프로그램
⌨️ 입력
- 첫째 줄에는 주어지는 명령의 수
- 둘째 줄부터는 명령이 하나씩 주어짐
🖥️ 출력
- 출력해야하는 명령이 주어질 때마다, 한 줄에 하나씩 출력
📄 처음으로 짠 코드
import sys
num = int(input())
queue = []
for i in range(num):
command = list(input().split())
if(command[0]=="push"):
queue.append(command[1])
elif(command[0]=="pop"):
if(len(queue)==0):
print(-1)
else:
print(queue.pop(0))
elif(command[0]=="size"):
print(len(queue))
elif(command[0]=="empty"):
if(len(queue) == 0):
print(1)
else:
print(0)
elif(command[0]=="front"):
if(len(queue)==0):
print(-1)
else:
print(queue[0])
else:
if(len(queue)==0):
print(-1)
else:
print(queue[-1])
🚨 오류들
- 시간초과 오류가 난다.
-> sys을 사용하여 stdin을 받으면 시간초과가 안 난다길래 해보았더니 성공!
📘 최종 코드
import sys
num = int(sys.stdin.readline())
queue = []
for i in range(num):
command = list(sys.stdin.readline().split())
if(command[0]=="push"):
queue.append(command[1])
elif(command[0]=="pop"):
if(len(queue)==0):
print(-1)
else:
print(queue.pop(0))
elif(command[0]=="size"):
print(len(queue))
elif(command[0]=="empty"):
if(len(queue) == 0):
print(1)
else:
print(0)
elif(command[0]=="front"):
if(len(queue)==0):
print(-1)
else:
print(queue[0])
else:
if(len(queue)==0):
print(-1)
else:
print(queue[-1])
🔎 알게 된 내용
- 여러 줄을 입력 받아야 할 때 input()을 입력하면 시간초과가 발생하기도 한다.
-> 따라서, sys.stdin.readline()으로 입력 받음