큐의 rotate 함수를 활용하는 문제이다. 코드는 다음과 같다
import sys
from collections import deque
N, K = map(int, sys.stdin.readline().split())
circle = deque(a for a in range(1,N + 1))
answer = list()
while circle:
circle.rotate(-K + 1)
answer.append(circle.popleft())
print('<', end = '')
for i in range(len(answer) - 1):
print(answer[i], end = ', ')
print( str(answer[-1]) + '>')
위의 내 풀이도 맞지만 format코드를 활용하여 더 간단하게 출력하는 것이 가능하다 다음은 chatGPT가 제시한 풀이다.
import sys
from collections import deque
N, K = map(int, sys.stdin.readline().split())
circle = deque(range(1, N + 1))
answer = []
while circle:
circle.rotate(-(K - 1)) # Rotate to bring the K-th person to the front
answer.append(circle.popleft()) # Remove the K-th person
# Using `join` for cleaner and faster output
print(f"<{', '.join(map(str, answer))}>")'알고리즘_파이썬' 카테고리의 다른 글
| 백준 18258번: 큐 2 (0) | 2025.03.11 |
|---|---|
| 백준 12789번: 도키도키 간식드리미 (0) | 2025.03.11 |
| 백준 10828 스택 (1) | 2024.02.07 |
| 백준 2884 알람 시계 (0) | 2024.02.03 |
| 백준 1929 소수 구하기 (0) | 2024.02.03 |