๐Ÿ”’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);