Algoritm

[백준] 10866번: 덱 (python)

ddori_c 2022. 7. 6. 01:18

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

 

10866번: 덱

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

www.acmicpc.net

  • 배열을 이용해서 구현했다
  • N의 범위가 10000까지 이므로, deque 배열에 None 10000개를 채워서 초기화 한다.
  • 함수를 사용해서 코드를 다시 짜면 보기에 예쁠것 같다
import sys
input = sys.stdin.readline

N = int(input())
mid = 5000
deque = [None for i in range(10000)] # N의 범위가 1~10000
head = mid # 시작지점 = 배열의 중간
tail = mid # 마지막 원소의 index+1
# print(deque)
# print(len(deque))

for _ in range(N):

    command = list(input().split())

    if command[0]== 'push_front':
        head -= 1
        # deque.insert(head,int(command[1])) # 처음에 deque를 None으로 채워두고 시작하니까, insert를 하면 그 값이 추가되어버림 (대체가 아니라)
        deque[head] = int(command[1])
        # print(deque)
        # print('head',head)

    if command[0]== 'push_back':
        # deque.insert(tail, int(command[1]))
        deque[tail] = int(command[1])
        tail += 1
        # print(deque)
        # print('tail',tail)

    if command[0]=='pop_front':
        if head == tail:
            print(-1)
        else:
            print(deque[head])
            # del deque[head] # pos만 옮겨주면 되는줄 -> 그래도 될걸? 나중에 덮어쓸거니까
            head += 1
            # print(deque)
            # print('head',head)

    if command[0]=='pop_back':
        if head == tail:
            print(-1)
        else:
            tail -= 1
            print(deque[tail])
            # print(deque)
            # print('tail',tail)
            # del deque[tail] # pos만 옮겨주면 되는줄

    if command[0]=='size':
        print(tail-head)
        # print(deque)

    if command[0]=='empty':
        if head == tail:
            print(1)
        else:
            print(0)

    if command[0] == 'front':
        if head == tail:
            print(-1)
        else:
            print(deque[head])
            # print(deque)

    if command[0] == 'back':
        if head == tail:
            print(-1)
        else:
            print(deque[tail-1])
            # print(deque)