[Baekjoon] 2023/3/19

장세민·2023년 3월 19일
0

BaekJoon

목록 보기
3/6

18258번

이 문제를 풀기 위해 내가 생각한 알고리즘은 다음과 같다.

  1. 명령의 수를 sys.stdin.readline으로 입력받는다.
  2. 시간 복잡도를 고려해서 collections 모듈의 deque를 이용하여 'push'와 ''pop' 명령을 구현한다.
  3. 나머지 명령들은 스택 구현시 사용했던 방법과 동일하게 구현한다.
import sys
from collections import deque
input = sys.stdin.readline

N = int(input())
que = deque()

for i in range(N):
    instruction = list(input().split())
    if len(instruction) == 2:
        que.append(int(instruction[1])) 
    else:
        if instruction[0] == 'pop':
            if len(que) == 0:
                print(-1)
            else:
                print(que.popleft())
        
        elif instruction[0] == 'size':
            print(len(que))
        
        elif instruction[0] == 'empty':
            print(int(len(que) == 0))
        
        elif instruction[0] == 'front':
            if len(que) == 0:
                print(-1)
            else:
                print(que[0])
        
        elif instruction[0] == 'back':
            if len(que) == 0:
                print(-1)
            else:
                print(que[-1])



2164번

이 문제를 풀기 위해 생각했던 알고리즘이다.

  1. 카드의 장 수(N)을 입력받는다.
  2. 1부터 N까지 카드를 큐에 넣는다.
  3. 큐의 크기 1보다 큰 경우(카드가 여러 장 남는경우), popleft를 이용하여
    맨 윗장을 버리고, append를 이용하여 그 다음 카드를 가장 뒤로 보낸다.
import sys
from collections import deque
input = sys.stdin.readline

N = int(input())
que = deque()

for i in range(N):
    que.append(i+1)

while(len(que) > 1):
    que.popleft()
    move = que.popleft()
    que.append(move)
        
print(que[0])



하루하루 꾸준하게 스택 쌓아보자.

profile
분석하는 남자 💻

0개의 댓글