티스토리 뷰

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

 

1874번: 스택 수열

1부터 n까지에 수에 대해 차례로 [push, push, push, push, pop, pop, push, push, pop, push, push, pop, pop, pop, pop, pop] 연산을 수행하면 수열 [4, 3, 6, 8, 7, 5, 2, 1]을 얻을 수 있다.

www.acmicpc.net

const fs = require('fs');
const [N,...nums] = fs.readFileSync("./dev/stdin").toString().trim().split("\n").map(v=>+v);

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 -1;
      const popItem = this.topOfStack;
      this.topOfStack = popItem.next;
      this.length-=1;

      return popItem.item
    }
  
    size(){
      return this.length;
    }
  
    empty(){
      if(this.length==0) return 1;
      else return 0;
    }
  
    top(){
      if(this.length==0)return -1;
      return this.topOfStack.item; 
    }
  
  }


let answer = [];
let now = 1;
let p = 0;
let stack = new Stack(); 
let success = true;
while(p<N){
    if(stack.size()==0){
        stack.push(now);
        answer.push('+')
        now++;
    }else if(stack.top()==nums[p]){
        stack.pop();
        answer.push('-')
        p++;
    }else{
        if(now>N) {
            success= false;
            break;
        }
        stack.push(now);
        answer.push('+')
        now++;
    }
}
if(success){
    console.log(answer.join('\n'));
}else{
    console.log('NO')
}
728x90
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/11   »
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 29 30
글 보관함