practivceAlgorithm/백준
[백준][Python] 1021 회전하는 큐
findTheValue
2021. 9. 28. 01:11
자주 나오는 문제. 처음엔 거리 계산해서 안움직이고 풀려했는데 실패. 아래에 안움직이는 코드도 찾아놓음.
import sys
input = sys.stdin.readline
from collections import deque
n, m = map(int, input().split())
position = list(map(int, input().split()))
q = deque([i for i in range(1, n+1)])
move = 0
for num in position:
if q.index(num) < len(q)/2:
while q[0] != num:
q.rotate(-1)
move += 1
else:
while q[0] != num:
q.rotate(1)
move += 1
if q[0] == num:
q.popleft()
continue
print(move)
안움직이고 중간에서 pop하는 코드
n, m = map(int, input().split())
dq = [i for i in range(1, n+1)]
ans = 0
for find in map(int, input().split()):
ix = dq.index(find)
ans += min(len(dq[ix:]), len(dq[:ix]))
dq = dq[ix+1:] + dq[:ix]
print(ans)