๐ŸŒฑ → ๐ŸŒณ

[๋ฐฑ์ค€] 10845๋ฒˆ : ํ python ๋ณธ๋ฌธ

Algorithms

[๋ฐฑ์ค€] 10845๋ฒˆ : ํ python

BAY 2023. 1. 6. 10:54
728x90

https://www.acmicpc.net/problem/10845

 

10845๋ฒˆ: ํ

์ฒซ์งธ ์ค„์— ์ฃผ์–ด์ง€๋Š” ๋ช…๋ น์˜ ์ˆ˜ N (1 ≤ N ≤ 10,000)์ด ์ฃผ์–ด์ง„๋‹ค. ๋‘˜์งธ ์ค„๋ถ€ํ„ฐ N๊ฐœ์˜ ์ค„์—๋Š” ๋ช…๋ น์ด ํ•˜๋‚˜์”ฉ ์ฃผ์–ด์ง„๋‹ค. ์ฃผ์–ด์ง€๋Š” ์ •์ˆ˜๋Š” 1๋ณด๋‹ค ํฌ๊ฑฐ๋‚˜ ๊ฐ™๊ณ , 100,000๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™๋‹ค. ๋ฌธ์ œ์— ๋‚˜์™€์žˆ์ง€

www.acmicpc.net

 

๋ฌธ์ œ ์ •๋ณด

ํ ์‹ค๋ฒ„4 20m O

์„ค๊ณ„ ๋ฐฉ๋ฒ•

queue class๋ฅผ ์„ค๊ณ„ ํ›„ ์ฝ”๋“œ ์ž‘์„ฑ

์ฝ”๋“œ

import sys
input = sys.stdin.readline

class Queue:
  def __init__(self):
    self.data = []
  def size(self):
    return len(self.data)
  def empty(self):
    if len(self.data) == 0:
      return 1
    else:
      return 0
  def push(self, x):
    self.data.append(x)
  def pop(self):
    if len(self.data) == 0:
      return -1
    else:
			# pop(0)์œผ๋กœ ํ•ด๋„ ๊ฐ™์Œ 
      ans = self.data[0]
      self.data = self.data[1:]
      return ans
  def front(self):
    if len(self.data) == 0:
      return -1
    else:
      return self.data[0]
  def back(self):
    if len(self.data) == 0:
      return -1
    else:
      return self.data[-1]

n = int(input())
queue = Queue()
for _ in range(n):
  cmd = input().split()
  op = cmd[0]
  if op == 'size':
    print(queue.size())
  elif op == 'empty':
    print(queue.empty())
  elif op == 'push':
    queue.push(cmd[1])
  elif op == 'pop':
    print(queue.pop())
  elif op == 'front':
    print(queue.front())
  elif op == 'back':
    print(queue.back())
  else:
    print('err')

๋‹ค๋ฅธํ’€์ด

์•„๋ž˜ ์ฝ”๋“œ์™€ ๊ฐ™์ด class๋ฅผ ๊ตฌํ˜„ํ•˜์ง€ ์•Š๊ณ ๋„ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ์Œ 

from sys import stdin

N = int(stdin.readline())
Que = []
for i in range(N) :
    A = stdin.readline().split()
    if A[0] == 'push' : Que.append(A[1])
    elif A[0] == 'pop' : 
        if Que : print(Que.pop(0))
        else : print(-1)
    elif A[0] == 'size' : print(len(Que))
    elif A[0] == 'empty' :
        if len(Que) == 0 : print(1)
        else : print(0)   
    elif A[0] == 'front' :
        if len(Que) == 0 : print(-1)
        else : print(Que[0])
    elif A[0] == 'back' :
        if len(Que) == 0 : print(-1)
        else : print(Que[-1])

์‹œ๊ฐ„ ๋ณต์žก๋„

$O(n)$

์–ด๋ ค์› ๋˜ ์ 

X

๋‹ค๋งŒ, python์„ ์ด์šฉํ•˜๋Š” ๊ฐ€์žฅ ํฐ ์ด์œ ๊ฐ€ ๋‚ด์žฅํ•จ์ˆ˜ ๋“ฑ์ด ์ž˜ ๋˜์–ด์žˆ๋‹ค๋Š” ๊ฑด๋ฐ ๊ทธ๊ฑธ ์ž˜ ํ™œ์šฉํ•˜์ง€ ๋ชป ํ•˜๊ณ  ์žˆ๋‹ค๊ณ  ํŒ๋‹จ๋˜์—ˆ๋‹ค,. python์˜ ๋‚ด์žฅํ•จ์ˆ˜๋“ค์„ ์กฐ๊ธˆ ๋” ์ตํ˜€์•ผ ํ•  ํ•„์š”๋ฅผ ๋Š๊ผˆ๋‹ค

์ฐธ๊ณ  ์ž๋ฃŒ

๋ฐฑ์ค€ 10845๋ฒˆ ํ(Queue) ํŒŒ์ด์ฌ(Python)

728x90