๐Algorithm
๋ฐฑ์ค[JS] > 1021๋ฒ ํ์ ํ๋ ํ
devWarrior
2024. 10. 30. 21:42
๐ฅ๋ฌธ์ ๋งํฌ
https://www.acmicpc.net/problem/1021
๐ฅํ์ด
์ฒ์์๋ ์ฐ์ฐํ์๋ฅผ ๊ณ ๋ คํด์ arr์ ๋ฐฐ์ด์์์ shift๋ฅผ ํ์ง์๊ณ ํธ๋ ์ค ์์๋๋ฐ ๊ตณ์ด ๊ทธ๋ฌ์ง ์๊ณ ๊ทธ๋ฅ shift์ push๋ฅผ ์ด์ฉํ๋ฉด ์ฝ๊ฒ ํ์ ์๋ค.
const fs = require("fs");
const input = fs.readFileSync("/dev/stdin").toString().split("\n");
const arr = input[1].split(" ").map((t) => Number(t));
const [n, m] = input[0].split(" ").map((t)=>Number(t));
let dic = [];
for (let i = 1; i <= n; ++i) {
dic.push(i);
}
const f1 = () => {
dic.shift();
};
const f2 = () => {
let v = dic.shift();
dic.push(v);
};
const f3 = () => {
let v = dic.pop();
dic.unshift(v);
};
let answer =0
for (let i = 0; i < arr.length; ++i) {
let target = arr[i];
if (dic[0] === target) {
f1();
} else {
let index = dic.indexOf(target)
let flag = dic.length/2
if (index < flag) {
while(dic[0]!==target){
f2();
answer+=1;
}
} else {
while(dic[0]!==target){
f3();
answer+=1;
}
}
f1();
}
}
console.log(answer);