[백준] - 2493 탑 (node.js)

밀루·2025년 4월 1일
0

BOJ

목록 보기
76/82

문제링크

풀이

스택을 사용했다. 스택에 숫자와 인덱스를 넣어두고 현재 숫자보자 큰 값이 나올 때까지 pop 하고, 현재 숫자보다 큰 값이 나오면 다시 stack에 넣어두고 pop한 인덱스를 저장하는 식으로 풀었다.

코드

const fs = require("fs");
const filePath = process.platform === "linux" ? "/dev/stdin" : "./input.txt";
let [n, arr] = fs.readFileSync(filePath).toString().trim().split("\n");

n = +n;
arr = arr.split(" ").map(Number);

let result = new Array(n).fill(0);
let stack = [[arr[0], 1]];
result[0] = 0;
for (let i = 1; i < n; i++) {
  while (stack.length) {
    const [s, idx] = stack.pop();
    if (s > arr[i]) {
      result[i] = idx;
      stack.push([s, idx]);
      stack.push([arr[i], i + 1]);
      break;
    }
  }
  if (!stack.length) stack.push([arr[i], i + 1]);
}

console.log(result.join(" "));

스택만 사용해서 문제 풀어본 건 처음이라.. 뭔가 신기방기

profile
이밀루의 도전

0개의 댓글