지민이는 N개의 원소를 포함하고 있는 양방향 순환 큐를 가지고 있다. 지민이는 이 큐에서 몇 개의 원소를 뽑아내려고 한다.
지민이는 이 큐에서 다음과 같은 3가지 연산을 수행할 수 있다.
큐에 처음에 포함되어 있던 수 N이 주어진다. 그리고 지민이가 뽑아내려고 하는 원소의 위치가 주어진다. (이 위치는 가장 처음 큐에서의 위치이다.) 이때, 그 원소를 주어진 순서대로 뽑아내는데 드는 2번, 3번 연산의 최솟값을 출력하는 프로그램을 작성하시오.
첫째 줄에 큐의 크기 N과 뽑아내려고 하는 수의 개수 M이 주어진다. N은 50보다 작거나 같은 자연수이고, M은 N보다 작거나 같은 자연수이다. 둘째 줄에는 지민이가 뽑아내려고 하는 수의 위치가 순서대로 주어진다. 위치는 1보다 크거나 같고, N보다 작거나 같은 자연수이다.
첫째 줄에 문제의 정답을 출력한다.
10 3
2 9 5
8
※ 해당 문제는 Deque를 이용하여 풀이하였으며, Deque 구현은 [알고리즘/자료구조] JavaScript 덱(Deque) 구현하기를 참고하여 구현했습니다.
const fs = require('fs');
let [n, input] = fs.readFileSync(0, 'utf-8').toString().trim().split('\n');
let N = Number(n.trim().split(' ')[0]);
let M = Number(n.trim().split(' ')[1]);
const array = input.trim().split(' ').map(Number);
class Deque {
constructor() {
(this.storage = []), (this.head = 0), (this.tail = 0);
}
push_front(value) {
if (this.storage[0]) {
for (let i = this.storage.length; i > 0; i--) {
this.storage[i] = this.storage[i - 1];
}
}
this.storage[this.head] = value;
this.tail++;
}
push_back(value) {
this.storage[this.tail++] = value;
}
pop_front() {
if (this.tail <= this.head) {
return null;
}
return this.storage[this.head++];
}
pop_back() {
if (this.tail <= this.head) {
return null;
}
return this.storage[--this.tail];
}
getFront() {
return this.storage[this.head];
}
find(value) {
let count = 0;
for (let i = this.head; i < this.tail; i++) {
if (this.storage[i] === value) {
return count;
}
count++;
}
return null;
}
size() {
return this.tail - this.head;
}
}
let deque = new Deque();
for (let i = 1; i <= N; i++) {
deque.push_back(i);
}
let remove = 0;
let num = 0;
let index = 0;
let count = 0;
while (true) {
if (remove === M) break;
num = deque.getFront();
if (num === array[index]) {
deque.pop_front();
index++;
remove++;
} else {
if (deque.find(array[index]) <= deque.size() / 2) {
deque.push_back(deque.pop_front());
} else {
deque.push_front(deque.pop_back());
}
count++;
}
}
console.log(count);
어려운 문제는 아니였지만, 덱을 구현하는 것에서 시간을 많이 쓰게 됐다. (queue보다 신경쓸 게 없긴하지만, 처음에는 storage를 객체로 구현했는데 push_front에서 복잡해져서 배열로 교체하는 등.. 은근 어려웠다.) 제출하고보니 코드 자체가 아쉬운 게 많다. 풀이 방법에서 서술했듯이 불필요한 변수 사용 등 아쉬운 점이 많지만.. 그래도 덱을 구현하니 굉장히 뿌듯했다. ㅎㅎ