반응형
문제
https://www.acmicpc.net/problem/1918
풀이
스택의 가장 위에있는 요소보다 우선순위가 낮은 연산자가 들어오면 스택을 비운다. 괄호를 만나면 괄호를 닫을 수 있을 때까지 스택을 비운다.
어제 푼 문제인데 오늘 그래픽스 수업에서 교수님이 말하셔서 놀랬다.. 역시 자료구조가 기본이다~
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 32 33 34 35 36 37 38 39 40 41 42 43 44 | def priority(x) : if x == "*" or x == "/" : return 2 elif x == "+" or x == "-" : return 1 elif x == "(" or x == ")" : return 0 return -1 def solve() : X = input() ans = "" stack = [] for c in X : p = priority(c) if c == '+' or c == '-' or c == '*' or c == '/': while stack and priority(stack[-1]) >= p : ans += stack.pop() stack.append(c) continue elif c == '(' : stack.append(c) continue elif c == ')' : while stack and stack[-1] != "(" : ans += stack.pop() stack.pop() continue ans += c while stack : ans += stack.pop() print(ans) solve() | cs |
반응형
'0 > algorithm' 카테고리의 다른 글
우선순위 큐 (priority queue), 힙 정렬 (heap sort) (0) | 2018.12.21 |
---|---|
정렬 알고리즘 (sorting algorithm) 정리 (0) | 2018.12.21 |
백준 5052번 전화번호 목록 (Python) (0) | 2018.11.12 |
백준 7576번 토마토 (Python) (0) | 2018.11.11 |
Kickstart Round A 2018 Problem A (0) | 2018.11.11 |