PS/백준
[백준] 2164번 카드2 (python)
yo0oni
2024. 7. 2. 16:21
https://www.acmicpc.net/problem/2164
문제 풀이
문제에 주어진 단계를 지켜가며 구현하면 된다. 이때 시간 초과가 날 수 있기 때문에 파이썬의 덱을 활용해서 O(1)으로 구현했다.
- 맨 위의 숫자를 popleft()로 버린다. 버리기 때문에 따로 변수에 저장하지 않는다.
- 그다음 숫자를 popleft()로 빼서 변수에 저장한 후 append()를 통해 맨 밑에 저장한다.
위 과정을 덱의 크기가 1 이하가 될 때까지 반복한다.
정답 코드
import sys
from collections import deque
input = sys.stdin.readline
n = int(input())
numbers = deque()
for i in range(1, n+1):
numbers.append(i)
while len(numbers) > 1:
numbers.popleft()
top = numbers.popleft()
numbers.append(top)
print(*numbers)