내 맴

[ BAEKJOON ] No. 18258 큐2 본문

Algorithm/Baekjoon 문제풀이

[ BAEKJOON ] No. 18258 큐2

뺙사우르수 2020. 4. 8. 17:10
728x90

문제 )

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

 

18258번: 큐 2

첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 2,000,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지 않은 명령이 주어지는 경우는 없다.

www.acmicpc.net

 

[ 풀이 ]

Queue을 사용해서 문제를 풀어준다

 

< Queue > 

: FIFO ( First In First Out ) 를 따르는 자료 구조 
먼저 집어넣은 data가 먼저 나온다. 

 

저번에 풀었던 스택 문제를 참조해서 코딩하였다. (코드가 겹침) 

https://luz0911.tistory.com/101?category=765467

 

[ BAEKJOON ] No. 10828 스택

문제 ) https://www.acmicpc.net/problem/10828 10828번: 스택 첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크..

luz0911.tistory.com

 

그러나 시간초과가 되어버렸다!

구글링을 해보니 collections모듈의 deque를 사용하면 해결 할 수 있다고 하길래 해봤더니 
시간 초과 없이 된다.

 

< collections.deque에 있는 method>


append(x) : list.append(x)와 같은 역할, deque의 오른쪽에 삽입
 appendleft(x): deque의 왼쪽에서 삽입
 pop(x) : list.pop(x)과 같은 역할 , 오른쪽 부터 제거
 popleft(x) : deque의 왼쪽부터 제거
 extend(x) : list.extend(x)와 같은 역할, deque의 오른쪽에 extend
 extendleft(x) : deque의 왼쪽부터 extend
 rotate(n) : deque안 elements를 n만큼 회전, n이 양수이면 오른쪽으로, 음수면 왼쪽으로 회전 
   

 

 

- python code

from collections import deque
import sys
input= sys.stdin.readline



def menu(command):
    if command[0]=='push':
        push(command[1])
    elif command[0]=='empty':
        empty()
    elif command[0]=='pop':
        Pop()
    elif command[0]=='size':
        Size()
    elif command[0]=='front':
        front()  
    elif command[0]=='back':
        back()

# push X
def push(X):
    queue.append(X)

# pop
def Pop():
    if not queue:
        print(-1)
    else:
        num=queue.popleft()
        print(num)

# size
def Size():
    print(len(queue))

# empty
def empty():
    if not queue:
        print(1)
    else:
        print(0)
# front
def front():
    if not queue:
        print(-1)
    else:
        print(queue[0])
# back
def back():
    if not queue:
        print(-1)
    else:
        print(queue[-1])

queue =deque([])
N=int(input())
for i in range(N):
    command =input().strip().split()
    menu(command)

 

728x90