티스토리 뷰
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
'자료구조 알고리즘 > 백준' 카테고리의 다른 글
Node.js) 백준 18258번 : 큐 2 (1) | 2021.09.13 |
---|---|
Node.js) 백준 17298 : 오큰수 ★ (0) | 2021.09.13 |
Node.js) 백준 4949번 : 균형 잡힌 세상 (0) | 2021.09.13 |
Node.js) 백준 9012번 : 괄호 (0) | 2021.09.13 |
Node.js) 백준 10773번 : 제로 (0) | 2021.09.13 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 동적프로그래밍
- 면접비
- 면접질문
- 롱베케이션
- node.js
- BFS
- 개발자면접
- 다이나밍프로그래밍
- 다이나믹프로그래밍
- 그래프
- MySQL
- 최소공통조상
- MOD
- KMP
- 투포인터 연습
- create db
- create databases;
- DB 생성
- 투포인터
- 은둔청년체험
- 서버개발
- 서버점검
- 로드나인
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 31 |
글 보관함