사용 언어 - Python3
10866번: 덱 (실버4, 큐)
문제 ★큐 문제★
10866번: 덱
첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지
www.acmicpc.net
정답
deque([]) 사용하기
(코드 풀이)
큐의 맨 앞(왼쪽)에 push => q. appendleft
큐의 맨 앞(왼쪽에 pop => q.popleft
q는 앞선 명령어들로 길이가 계속 달라지므로 인덱싱할 때 주의해야한다.
가장 오른쪽 값 출력 => d[len(d)-1]
# 정답
import sys
from collections import deque
d = deque()
n = int(input())
for i in range(n):
c = sys.stdin.readline().split()
if c[0] == 'push_front':
d.appendleft(c[1]) #앞에 push = appendleft
elif c[0] == 'push_back':
d.append(c[1])
elif c[0] == 'pop_front':
if d:
print(d[0])
d.popleft()
else:
print("-1")
elif c[0] == 'pop_back':
if d:
print(d[len(d)-1])
d.pop()
else:
print("-1")
elif c[0] == 'size':
print(int(len(d)))
elif c[0] == 'empty':
if d:
print("0")
else:
print("1")
elif c[0] == 'front':
if d:
print(d[0])
else:
print("-1")
elif c[0] == 'back':
if d:
print(d[len(d)-1])
else:
print("-1")
레퍼런스
- 정답 참고
[백준] 덱 10866번 파이썬 Python 자료구조
문제의 제목대로 데크를 사용해서 문제를 수월하게 풀 수 있다.데크 deque 설명글push_front일 때appendleft() 함수를 이용.pop_front일 때popleft() 함수를 이용.
velog.io
- 정답 깃허브
GitHub - yyeongeun/codingtest: 코딩테스트 공부
코딩테스트 공부. Contribute to yyeongeun/codingtest development by creating an account on GitHub.
github.com
'Algorithm > 스택&큐&덱&힙' 카테고리의 다른 글
[백준] 5430번 AC (1) | 2023.01.22 |
---|---|
[백준] 1021번 회전하는 큐 (0) | 2023.01.22 |
[백준] 1966번 프린터 큐 (0) | 2023.01.22 |
[백준] 11866번 요세푸스 문제0 (1) | 2023.01.22 |
[백준] 2164번 카드2 (0) | 2023.01.22 |
댓글