상세 컨텐츠

본문 제목

Boj 큐2 python

Algorithm/algorithm feedback

by 개복신 개발자 2021. 7. 23. 15:11

본문

728x90
반응형

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

 

18258번: 큐 2

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

www.acmicpc.net


내 풀이

import sys
from collections import deque

input=sys.stdin.readline

class Que:
    def __init__(self):
        self.list=deque()
    def push(self, num):
        self.list.append(num)
    def pop(self):
        if self.list:
            pop_num=self.list[0]
            self.list.popleft()
            return pop_num
        else:
            return -1
    def size(self):
        return len(self.list)
    def empty(self):
        if self.list:
            return 0
        else:
            return 1
    def front(self):
        if self.list:
            return self.list[0]
        else:
            return -1
    def back(self):
        if self.list:
            return self.list[-1]
        else:
            return -1

n=int(input())
dq=Que()
for i in range(n):
    command=input().split()
    if command[0]=="push":
        dq.push(int(command[1]))

    elif command[0]=="pop":
        print(dq.pop())

    elif command[0]=="size":
        print(dq.size())

    elif command[0]=="empty":
        print(dq.empty())

    elif command[0]=="front":
        print(dq.front())

    elif command[0]=="back":
        print(dq.back())

-시간초과가 뜨는 오류가 발생함

1.import sys

input=sys.stdin.readline

코드 작성

 

2.class Que에서 pop 함수가 작동할 때 리스트의 가장 앞의 요소가 나가고 다시 정렬하면

계산 시간이 오래 걸려서 시간초과가 뜬다

따라서 from collections import deque

self.list.popleft() 코드를 작성하면 오류가 해결된다

 

만약 이런 식으로 코드를 작성하지 않고 self.list[0:]로 작성하면 시간 초과가 뜬다

 

반응형

'Algorithm > algorithm feedback' 카테고리의 다른 글

Boj 1991 트리 순회 python  (0) 2021.07.29
Boj 15828 Router python  (0) 2021.07.23
Boj 9012 괄호 python  (0) 2021.07.22
Boj 10828 스택 python  (0) 2021.07.19
Boj 3079 입국심사 python  (0) 2021.07.16

관련글 더보기

댓글 영역