Coding Test/Baekjoon

[Python] 파이썬(2164) 백준 카드2

파송송 2023. 5. 4. 14:49
728x90

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


나의 풀이

  • N장의 카드가 있을 때 카드는 1~N까지 정렬되어 있다.
  • 맨 위의 카드를 버리고 그다음 맨 위 카드를 맨 아래로 옮길 때 마지막에 남은 카드는 무언인지 구하는 문제이다.

맨 위의 카드를 pop()하고 그다음 카드를 저장하여 아래에 넣어서 문제를 해결했다.

import sys
from collections import deque

num = int(sys.stdin.readline())
card = deque([i+1 for i in range(num)])

while len(card) > 1:
    card.popleft()
    top_card = card.popleft()
    card.append(top_card)

print(card[0])


다른 사람의 풀이

deque의 rotate를 사용함

rotate가 있다는 건 처음 알아서 이 참에 기억하고 다른 문제에 사용해야겠다.

import sys
from collections import deque

num = int(sys.stdin.readline)
arr = deque(range(1,num+1))

while len(arr) > 1:
    arr.popleft()
    arr.rotate(-1)
print(arr[0])

728x90