https://www.acmicpc.net/problem/1021
이 문제는 덱
문제이다. 아래만 기억해 두면 쉽게 풀 수 있다.
첫 번째 원소를 뽑아낸다.(arr.shift())
왼쪽으로 한 칸 이동시킨다.(arr.push(arr.shift()))
오른쪽으로 한 칸 이동 (arr.unshift(arr.pop()))
Array.from
으로 1부터 N까지의 정수로 초기화시킨다.deque.indexOf(idx) < deque.length - deque.indexOf(idx)
즉, 오른쪽으로 빼는 것이 빠른지, 왼쪽으로 빼는 것이 빠른지 계산하여 연산을 수행하면 된다.const fs = require("fs");
const stdin = (
process.platform === "linux"
? fs.readFileSync("/dev/stdin").toString().trim()
: `10 3
2 9 5`
).split("\n");
const input = (() => {
let line = 0;
return () => stdin[line++];
})();
const [N, M] = input().split(" ").map(Number);
const target = input().split(" ").map(Number);
const deque = Array.from(Array(N), function (value, index) {
return index + 1;
});
let calcCnt = 0;
for (const idx of target) {
while (true) {
if (deque.indexOf(idx) === 0) {
deque.shift();
break;
}
if (deque.indexOf(idx) < deque.length - deque.indexOf(idx)) {
deque.push(deque.shift());
calcCnt += 1;
} else {
deque.unshift(deque.pop());
calcCnt += 1;
}
}
}
console.log(calcCnt);
백준 문제는 해독하기가 가끔 힘들 때가 있는데 그게 오늘이었다. 2번, 3번 연산의 최솟값을 출력
이라는 말이 조건문의 2번 3번이 아니라, 2번 연산을 한 뒤, 3번 연산을 한 뒤
로 이해해버려서 푸는데 시간이 오래 걸린 것 같다.
데브코스를 하면서 함수에 대해서 기존에 알고 있던 방식보다 더 효율적인 방법들을 조금씩 배워가는 것 같아서 매우 좋다.😀💕
스택, 큐, 덱을 많이 구현해보면서 빨리 익숙해 질 수 있으면 좋겠다.