[백준(python)] 24511_queuestack

구준희·2024년 2월 7일
0

알고리즘

목록 보기
29/31
post-thumbnail

📌 난이도, 유형

난이도 : 실버3
유형 : 자료구조, 스택, 덱, 큐
시간제한 : 1초(추가 시간 없음)
메모리제한 : 1024MB(추가 메모리 없음)


📌 문제설명


📌 입출력 예


📄 코드

틀린코드

import sys
from collections import deque

input = sys.stdin.readline
n = int(input().rstrip())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
m = int(input().rstrip())
C = list(map(int, input().split()))
queue = deque()
for i in range(m):
    move = C[i]
    for j in range(n):
        if A[j] == 0:  # 큐일 경우(기존거 빼기)
            t = B[j]
            B[j] = move
            move = t
        else:  # 스택일 경우(새로 들어온애 빼기)
            continue
    print(move, end=" ")

정답코드

import sys
from collections import deque

input = sys.stdin.readline
n = int(input().rstrip())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
m = int(input().rstrip())
C = list(map(int, input().split()))
queue = deque()

for i in range(n):
    if A[i] == 0:
        queue.append(B[i])
for i in C:
    queue.appendleft(i)
for i in range(m):
    print(queue.pop(), end=" ")

📝 해설

문제를 그냥 풀면 시간초과가 난다..

문제의 핵심은 스택은 무시하고 큐만 계산하는 것이다 즉, '큐를 여러개 이어붙이면 어떻게 되는가?'이다.
A : [0, 1, 1, 0]
B : [1, 2, 3, 4]
B를 스택만 제거하고 큐만 남기면
B : [1, 4]가 된다.

여기에 수열 M : [2, 4, 7]을 문제의 조건에 따라 계산해보면 B는
[1, 4] -> [2, 1] -> [4, 2] -> [7, 4]

이런 식으로 큐처럼 계산되므로 B에 리스트 M을 다 넣어주고 m만큼 popleft를 해주면 된다.

profile
꾸준히합니다.

0개의 댓글