새소식

Problem solving/문제 풀이 - 2022.04.16

[파이썬] 백준 18258번 큐 2 - 링크드 리스트로 구현하기

  • -
 

18258번: 큐 2

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

www.acmicpc.net

시간 제한

1초

메모리 제한

512mb

문제

정수를 저장하는 큐를 구현한 다음, 입력으로 주어지는 명령을 처리하는 프로그램을 작성하시오.

명령은 총 여섯 가지이다.

  • push X: 정수 X를 큐에 넣는 연산이다.
  • pop: 큐에서 가장 앞에 있는 정수를 빼고, 그 수를 출력한다. 만약 큐에 들어있는 정수가 없는 경우에는 -1을 출력한다.
  • size: 큐에 들어있는 정수의 개수를 출력한다.
  • empty: 큐가 비어있으면 1, 아니면 0을 출력한다.
  • front: 큐의 가장 앞에 있는 정수를 출력한다. 만약 큐에 들어있는 정수가 없는 경우에는 -1을 출력한다.
  • back: 큐의 가장 뒤에 있는 정수를 출력한다. 만약 큐에 들어있는 정수가 없는 경우에는 -1을 출력한다.

입력

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

출력

출력해야하는 명령이 주어질 때마다, 한 줄에 하나씩 출력한다.

예제 입력 1 

15
push 1
push 2
front
back
size
empty
pop
pop
pop
size
empty
pop
push 3
empty
front

예제 출력 1 

1
2
2
0
1
2
-1
0
1
-1
0
3

나의 풀이

deque를 사용하지 않고 푸는 것을 목표로 했다.

이때 시간 제한과 입력 수를 고려해 모든 시간 복잡도를 $O(1)$로 구성하려고 했다. 

 

처음 풀이

list로 풀기 시도 -> 시간 초과 발생

 

이유?

  • pop(0)의 시간 복잡도는 $O(1)$이 아니고 $O(n)$이다.
  • pop(0) 실행 시 기존 list의 순서를 모두 한칸 씩 옮겨야 하기 때문.

결국 list로는 구성할 수 없기 때문에 자료 구조를 직접 만들어서 푸는 방향으로 선회.

import sys

class queue():
    def __init__(self):
        self.queue = []
    # push 함수
    def push(self, x : int):
        self.queue.append(x)
    # pop 함수    
    def pop(self):
        try:
            print(self.queue[0])
        except IndexError:
            print(-1)
        self.queue = self.queue[1:]
    # size 함수
    def size(self):
        print(len(self.queue))
    # empty 함수
    def empty(self):
        print(1 if len(self.queue) == 0 else 0)
    # front 함수
    def front(self):
        try:
            print(self.queue[0])
        except IndexError:
            print(-1)
    # back 함수
    def back(self):
        try:
            print(self.queue[-1])
        except IndexError:
            print(-1)

queue = queue()
# 명령어 미리 저장
case = {
    "pop" : lambda queue : queue.pop(),
    "size" : lambda queue : queue.size(),
    "empty" : lambda queue : queue.empty(),
    "front" : lambda queue : queue.front(),
    "back" : lambda queue : queue.back()
    }
n = int(input())
for _ in range(n):
    # 명령 수가 많아서 sys로 받음
    command = sys.stdin.readline().rstrip().split()
    if command[0] == "push":
        queue.push(int(command[1]))
    else:
        case[command[0]](queue)

 

 

수정 풀이

간단한 singly linked list로 구현

https://www.javatpoint.com/linked-list-implementation-of-queue

  • 원소 개수를 따로 세주기 위해서 self.num 인스턴스 변수 추가
  • 시간 복잡도가 $O(1)$인데도 통과가 안돼서 pypy로 제출했다.
"""
시간 복잡도 1로 만들기 위해서 linked list로 구현
- 시간 복잡도 1인데도 시간 초과가 나와 pypy로 변경해서 통과
"""
import sys
class Node():
    def __init__(self, data):
        self.data = data
        self.next = None
        
class Queue():
    def __init__(self):
        self.f = None
        self.r = None
        self.num = 0
    # push 함수
    def push(self, x : int):
        temp = Node(x)
        if not self.f:
            self.f = self.r = temp
        else:
            self.r.next = temp
            self.r = temp
        self.num += 1    
    # pop 함수    
    def pop(self):
        if self.num == 0:
            print(-1)
            return
        print(self.f.data)
        temp = self.f
        self.f = temp.next
        self.num -= 1
    # size 함수
    def size(self):
        print(self.num)
    # empty 함수
    def empty(self):
        print(1 if self.num == 0 else 0)
    # front 함수
    def front(self):
        if self.num == 0:
            print(-1)
            return
        print(self.f.data)
    # back 함수
    def back(self):
        if self.num == 0:
            print(-1)
            return
        print(self.r.data)

queue = Queue()
# 명령어 미리 저장
case = {
    "pop" : lambda queue : queue.pop(),
    "size" : lambda queue : queue.size(),
    "empty" : lambda queue : queue.empty(),
    "front" : lambda queue : queue.front(),
    "back" : lambda queue : queue.back()
    }
    
n = int(input())
for _ in range(n):
    # 명령 수가 많아서 sys로 받음
    command = sys.stdin.readline().rstrip().split()
    if command[0] == "push":
        queue.push(int(command[1]))
    else:
        case[command[0]](queue)

다른 사람 풀이

deque를 사용한 풀이이다.

구현해야되는 것이 아니라면 앞으로는 deque를 불러와서 쓰도록 하자.

import sys
from collections import deque
n = int(sys.stdin.readline())
q = deque([])
for i in range(n):
    s = sys.stdin.readline().split()
    if s[0] == 'push':
        q.append(s[1])
    elif s[0] == 'pop':
        if not q:
            print(-1)
        else:
            print(q.popleft())
    elif s[0] == 'size':
        print(len(q))
    elif s[0] == 'empty':
        if not q:
            print(1)
        else:
            print(0)
    elif s[0] == 'front':
        if not q:
            print(-1)
        else:
            print(q[0])
    elif s[0] == 'back':
        if not q:
            print(-1)
        else:
            print(q[-1])

 

 

[백준] 18258번(python 파이썬)

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

pacific-ocean.tistory.com

 

Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.