티스토리 뷰

https://www.acmicpc.net/problem/2493

 

2493번: 탑

첫째 줄에 탑의 수를 나타내는 정수 N이 주어진다. N은 1 이상 500,000 이하이다. 둘째 줄에는 N개의 탑들의 높이가 직선상에 놓인 순서대로 하나의 빈칸을 사이에 두고 주어진다. 탑들의 높이는 1

www.acmicpc.net

const fs = require('fs');
const input = fs.readFileSync('./dev/stdin').toString().trim().split('\n');
const top = input[1].split(' ').map(Number);

class Node {
        constructor(item) {
                this.item = item;
                this.next = null;
        }
}

class Stack {
        constructor() {
                this.topOfStack = null;
                this.length = 0;
        }

        push(item) {
                const node = new Node(item);
                if (this.topOfStack != null) {
                        node.next = this.topOfStack;
                }
                this.topOfStack = node;
                this.length += 1;
        }

        pop() {
                if (this.length == 0) return '';
                const popItem = this.topOfStack;
                this.topOfStack = popItem.next;
                this.length -= 1;

                return popItem.item;
        }

        size() {
                return this.length;
        }

        empty() {
                if (this.length == 0) return true;
                else return false;
        }

        top() {
                if (this.length == 0) return false;
                return this.topOfStack.item;
        }
}

let answer = [];
const stack = new Stack();
stack.push([top[0], 1]);
answer[0] = 0;

for (let i = 1; i < top.length; i++) {
        const now = top[i];
        if (stack.top()[0] > now) {
                answer[i] = stack.top()[1];
                stack.push([now, i + 1]);
        } else {
                while (stack.top()[0] < now) {
                        stack.pop();
                        if (stack.empty()) break;
                }

                if (stack.empty()) {
                        stack.push([now, i + 1]);
                        answer[i] = 0;
                } else {
                        answer[i] = stack.top()[1];
                        stack.push([now, i + 1]);
                }
        }
}
console.log(answer.join(' '));
728x90
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
글 보관함