[Baekjoon] 1874 스택 수열(파이썬 python)
이번 문제는 아래 링크에서 풀어볼 수 있습니다.
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
문제
스택 (stack)은 기본적인 자료구조 중 하나로, 컴퓨터 프로그램을 작성할 때 자주 이용되는 개념이다. 스택은 자료를 넣는 (push) 입구와 자료를 뽑는 (pop) 입구가 같아 제일 나중에 들어간 자료가 제일 먼저 나오는 (LIFO, Last in First out) 특성을 가지고 있다.
1부터 n까지의 수를 스택에 넣었다가 뽑아 늘어놓음으로써, 하나의 수열을 만들 수 있다. 이때, 스택에 push하는 순서는 반드시 오름차순을 지키도록 한다고 하자. 임의의 수열이 주어졌을 때 스택을 이용해 그 수열을 만들 수 있는지 없는지, 있다면 어떤 순서로 push와 pop 연산을 수행해야 하는지를 알아낼 수 있다. 이를 계산하는 프로그램을 작성하라.
입력
첫 줄에 n (1 ≤ n ≤ 100,000)이 주어진다. 둘째 줄부터 n개의 줄에는 수열을 이루는 1이상 n이하의 정수가 하나씩 순서대로 주어진다. 물론 같은 정수가 두 번 나오는 일은 없다.
출력
입력된 수열을 만들기 위해 필요한 연산을 한 줄에 한 개씩 출력한다. push연산은 +로, pop 연산은 -로 표현하도록 한다. 불가능한 경우 NO를 출력한다.
예제 입력 1
8
4
3
6
8
7
5
2
1
예제 출력 1
+
+
+
+
-
-
+
+
-
+
+
-
-
-
-
-
예제 입력 2
5
1
2
5
3
4
예제 출력 2
NO
힌트
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]을 얻을 수 있다.
정답 코드
답안 1
파이썬 Ver.
import sys n = int(sys.stdin.readline().rstrip()) def answer1(n): stack = [] result = [] count = 1 for _ in range(n): data = int(sys.stdin.readline().rstrip()) while count <= data: stack.append(count) result.append("+") count += 1 if stack.pop() == data: result.append("-") else: print("NO") exit(0) print("\n".join(result)) answer1(n)
자바스크립트/NodeJS Ver.const fs = require('fs'); const filePath = process.platform === 'linux' ? '/dev/stdin' : './input.txt'; let input = fs .readFileSync(filePath) .toString() .trim() .split('\n') .map((val) => parseInt(val)); const n = input.splice(0, 1); const answer1 = (n, data) => { const stack = []; const result = []; let count = 1; for (let num of data) { while (count <= num) { stack.push(count); result.push('+'); count++; } if (stack.pop() === num) { result.push('-'); } else { return 'NO'; } } return result.join('\n'); }; console.log('answer1', answer1(n, input));
답안 2
파이썬 Ver.
import sys n = int(sys.stdin.readline().rstrip()) def answer2(n): stack, result, count, isPossible = [], [], 1, True for _ in range(n): data = int(sys.stdin.readline().rstrip()) while count <= data: stack.append(count) result.append("+") count += 1 if stack.pop() == data: result.append("-") else: isPossible = False break if not isPossible: print("NO") else: for ret in result: print(ret) answer2(n)
자바스크립트/NodeJS Ver.
const fs = require('fs'); const filePath = process.platform === 'linux' ? '/dev/stdin' : './input.txt'; let input = fs .readFileSync(filePath) .toString() .trim() .split('\n') .map((val) => parseInt(val)); const n = input.splice(0, 1); const answer2 = (n, data) => { const [stack, result] = [[], []]; let [count, isPossible] = [1, true]; for (let num of data) { while (count <= num) { stack.push(count); result.push('+'); count++; } if (stack.pop() === num) { result.push('-'); } else { isPossible = false; break; } } if (!isPossible) { return 'NO'; } else { return result.join('\n'); } }; console.log('answer2', answer2(n, input));
문제 풀이
스택의 작동 원리를 알아야 풀 수 있는 문제이다. 스택은 LIFO(Last In First Out)으로 동작한다. 위 문제에서는 주어진 입력값과 count가 똑같아질 때까지 count를 1씩 증가시키며 스택에 쌓는다. 또한 append 메서드로 push 동작을 했으므로 result 리스트에 '+'를 추가한다. 이때 스택 내 맨 위의 값이 입력값과 같아지면 pop 메서드로 스택 내 맨 위의 값을 제거하고 result 리스트에 '-'를 추가한다. count가 입력값에 이르렀는데도 스택 내 맨 위의 값과 입력값이 불일치한다면 수열을 만들 수 없으므로 NO를 반환한다. 반복문을 다 통과했다면 result 리스트 내 결괏값들을 차례대로 반환한다.
함께 보기
https://computer-science-student.tistory.com/576
[파이썬, Python] 백준 1874번 : 스택 수열
백준 1874번 : 스택 수열 (문제 바로가기) 내 코드 n = int(input()) count = 1 stack = [] result = [] for _ in range(n): data = int(input()) while count
computer-science-student.tistory.com
https://assaeunji.github.io/python/2020-05-04-bj1874/
[백준] 1874번 스택 수열 파이썬 풀이
난이도: 하 풀이시간: 20분 분류: 스택 링크: [link]
assaeunji.github.io
https://wook-2124.tistory.com/440
백준 알고리즘 | 1874 : 스택 수열 (Python / 파이썬)
스택 수열 성공분류 시간 제한 메모리 제한 제출 정답 맞은 사람 정답 비율 2 초 128 MB 42980 13832 10074 32.501% https://www.acmicpc.net/problem/1874 1874번: 스택 수열 1부터 n까지에 수에 대해 차례로 [push, push, p
wook-2124.tistory.com
https://hongcoding.tistory.com/39
[백준] 1874번 스택 수열 (Python 파이썬)
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]을 얻을 수 있
hongcoding.tistory.com