[python]스택/큐_백준 문제풀이

이희진·2023년 3월 3일
0

스택(stack)과 큐(queue)에 개념

https://velog.io/@lhj99apr/%EC%BD%94%ED%85%8C-%EA%B3%B5%EB%B6%80-%EC%8A%A4%ED%83%9D%EA%B3%BC-%ED%81%90

(스택) 백준 10773번 - 제로

문제 링크 -https://www.acmicpc.net/problem/10773

K = int(input())
stack = []
for k in range(K):
    n = int(input())
    if n != 0:
        stack.append(n)
    else:
        stack.pop()

print(sum(stack))

(스택) 백준 9012번 - 괄호

문제 링크 - https://www.acmicpc.net/problem/9012

T = int(input())


for t in range(T):
    flag = 0
    ps = list(input())
    while len(ps) > 0:
        if flag < 0:
            break
        else:
            x = ps.pop()
            if x == ')':
                flag += 1
            else:
                flag -= 1
    if len(ps) == 0 and flag == 0: 
        print("YES")
    else:
        print("NO")

(스택) 백준 1874번 - 스택 수열

문제 링크 - https://www.acmicpc.net/problem/1874

import sys
input = sys.stdin.readline


def sol(seq):
  i = 1
  ans = []
  stack = []
  for num in seq:
      while i <= num:
          stack.append(i)
          ans.append('+')
          i += 1

      if stack.pop() != num: return "NO"
      ans.append('-')
  return '\n'.join(ans)


if __name__ == "__main__":
  n = int(input())
  seq = [int(input()) for _ in range(n)]
  print(sol(seq))

(큐) 백준 18258번 - 큐 2

문제 링크 - https://www.acmicpc.net/problem/18258

import sys
from collections import deque
n = int(input())
q = deque()

for i in range(n):
  command = sys.stdin.readline().split()
  if command[0] == 'push':
      q.append(command[1])
  elif command[0] == 'pop':
      if len(q) > 0:
          print(q.popleft())
      else:
          print(-1)
  elif command[0] == 'size':
      print(len(q))
  elif command[0] == 'empty':
      if len(q) == 0:
          print(1)
      else:
          print(0)
  elif command[0] == 'front':
      if len(q) > 0:
          print(q[0])
      else:
          print(-1)
  elif command[0] == 'back':
      if len(q) > 0:
          print(q[-1])
      else:
          print(-1)

(큐) 백준 2164번 - 카드 2

문제 링크 -https://www.acmicpc.net/problem/2164

from collections import deque

N = int(input())
q = deque([x for x in range(1, N+1)])

while len(q) > 1:
    q.popleft()
    x = q.popleft()
    q.append(x)

print(q[0])

(큐) 백준 11866번 - 요세푸스 순열

문제 링크 - https://www.acmicpc.net/problem/11866
이 문제는 n명의 사람이 원을 이루어 앉아 있고, 1번부터 시작하여 순서대로 k번째 사람을 제거한다고 할 때, 제거되는 순열을 구하는 문제이다.

from collections import deque
n, k = map(int, input().split(' '))
queue = deque([x for x in range(1, n+1)])
remove = []

while queue:
    for i in range(k-1):
        x = queue.popleft()
        queue.append(x)
    x = queue.popleft()
    remove.append(x)
    
print('<'+", ".join(map(str, remove))+'>')

0개의 댓글