ZZIN33
re-code-cord
ZZIN33
전체 방문자
오늘
어제
  • 분류 전체보기 (52)
    • Paper (4)
      • Generative Model (2)
      • Segmentation (1)
      • 모델 경량화 (1)
    • Study (34)
      • AI (10)
      • MLOps (8)
      • CS (4)
      • OpenCV (1)
      • Algorithm (9)
      • ETC (2)
    • Project (6)
    • ETC (8)
      • 부스트캠프 AI Tech (2)
      • 도서 리뷰 (5)

블로그 메뉴

  • Home
  • About
  • Github

인기 글

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
ZZIN33

re-code-cord

[백준] 5430번: AC (Python)
Study/Algorithm

[백준] 5430번: AC (Python)

2021. 11. 29. 22:07

문제는 어렵지 않으나, 입출력을 약간 번거로운 편인 문제.

 

import sys
from collections import deque

for test_case in range(int(sys.stdin.readline())):
  error = False

  command_list = sys.stdin.readline().strip()
  num_cnt = int(sys.stdin.readline())
  num_list = deque(sys.stdin.readline().strip()[1:-1].split(","))
  
  if num_cnt == 0:
    num_list = deque()

  for command in command_list:
    if command == "R":
      num_list.reverse()
    else: 
      if num_list:
        num_list.popleft()
      else:
        error = True
        break
      
  if error:
    print("error")
  else:
    print("["+",".join(num_list)+"]")

다음과 같이 코드를 작성했으나, 시간초과 발생.
list를 deque로 변경하고 다시 제출했으나, 여전히 시간초과가 발생했다.
원인을 찾아보니 num_list가 굉장히 길다보니, reverse()를 수행하는 시간이 상당히 걸리는 것으로 보인다.
reverse()를 최대한 사용하지 않도록 코드를 수정했다.

import sys
from collections import deque

for test_case in range(int(sys.stdin.readline())):
  error = False
  reverse = False

  command_list = sys.stdin.readline().strip()
  num_cnt = int(sys.stdin.readline())
  num_list = deque(sys.stdin.readline().strip()[1:-1].split(","))
  
  if num_cnt == 0:
    num_list = deque()

  for command in command_list:
    if command == "R":
      if reverse:
        reverse = False
      else:
        reverse = True

    else: 
      if num_list:
        if reverse:
          num_list.pop()
        else:
          num_list.popleft()
      else:
        error = True
        break
      
  if error:
    print("error")
  elif reverse:
    num_list.reverse()
    print("["+",".join(num_list)+"]")
  else:
    print("["+",".join(num_list)+"]")

 

 

keypoint

  • list 대신 deque() 사용하기
  • 직접 reverse() 대신 변수로 reverse 상태인지 기억하기 
저작자표시

'Study > Algorithm' 카테고리의 다른 글

[프로그래머스] 주식가격 (Python)  (0) 2021.12.02
[백준] 9663번 : N-Queen (Python)  (0) 2021.11.30
[백준] 10828번: 스택 (Python)  (0) 2021.11.25
[백준] 1920번: 수 찾기, 10815번: 숫자 카드 (Python)  (0) 2021.11.25
[백준] 2108번: 통계학 (Python)  (0) 2021.11.24

    티스토리툴바