[백준 2346번] 풍선 터뜨리기

박형진·2022년 3월 14일
0

1. 문제 링크

풍선 터뜨리기


2. 코드

import sys

n = int(sys.stdin.readline().rstrip())
arr = list(map(int, sys.stdin.readline().rstrip().split()))
q = []
for i in range(1, n + 1):
    q.append((i, arr[i - 1]))
idx = 0
move = q.pop(0)[1]
result = [1]
while q:
	# 오른쪽(+) 방향 이동
    if move >= 0:
        idx = (idx + move - 1) % len(q)
    # 왼쪽(-) 방향 이동
    else:
        idx = (idx + move) % len(q)
    ans, move = q.pop(idx)
    result.append(ans)
    
for r in result:
    print(r, end=' ')

+ rotate() 함수를 이용한 풀이

import sys
from collections import deque

n = int(input())
arr = list(map(int, sys.stdin.readline().rstrip().split()))
q = deque()
for i in range(1, n + 1):
    q.append((i, arr[i - 1]))
result = []
# rotate 풀이의 핵심, 위치를 조절하여 0번째 원소가 항상 제거되는 값이 되게 만들자.
# 인덱스를 고민하지않고 popleft() 만 사용하여 풀 수 있는 장점이 있다.
while q:
    ans, move = q.popleft()
    result.append(ans)
    # 양의 이동일 경우
    if move >= 0:
        q.rotate(-(move - 1))
    # 음의 이동일 경우
    else:
        q.rotate(-move)
for r in result:
    print(r, end=' ')

3. 후기

1158번 요세푸스 문제는 양의 이동만을 고려했다면, 이 문제는 음의 이동도 고려해야 한다.

  • 오른쪽 이동의 경우 pop() 을 하게 될 때, 모든 리스트가 한 칸씩 당겨지게 되므로 -1 을 통해 값을 보정해준다.

  • 왼쪽 이동의 경우 -1 을 따로 해줄 필요 없이 계산을 하면 된다.

글로 이해하려기 보다는 두 경우 모두 직접 예시를 그려보면 쉽게 이해할 수 있을 것이다.

profile
안녕하세요!

0개의 댓글