이건 후위표기식(1918)보다 더 쉽다.
피연산자 (이 문제에서는 대문자)가 나온다면 스택에 넣다가
연산자 (+,-,*,/)를 만나면 스택에서 2개의 데이터를 꺼내 연산자에 따라 계산하면 된다.
-C++
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 | #include<iostream> #include<stack> using namespace std; stack<double> st; int arr[27]; int main(void){ cin.tie(0); cout.tie(0); ios_base :: sync_with_stdio(false); int n; string str; cin >> n; cin >> str; for(int i=0; i<n; i++) cin >> arr[i]; int size = str.length(); char ch; double num1, num2; for(int i=0; i<size; i++){ ch = str[i]; if(ch=='+' || ch=='-' || ch=='*' || ch=='/'){ num2=(double)st.top(); st.pop(); num1=(double)st.top(); st.pop(); if(ch=='+') st.push(num1+num2); else if(ch=='-') st.push(num1-num2); else if(ch=='*') st.push(num1*num2); else st.push(num1/num2); } else if('A'<=ch && ch <='Z'){ st.push(arr[ch-'A']); } } double ans = st.top(); cout << fixed; cout.precision(2); cout << ans; return 0; } | cs |
- JAVA
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 | import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.util.Stack; public class Main{ public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); Stack<Double> st = new Stack<Double>(); int n = Integer.parseInt(br.readLine()); Double[] arr = new Double[n]; String str = br.readLine(); for(int i=0; i<n; i++) arr[i] = Double.parseDouble(br.readLine()); int size = str.length(); char ch; Double num1, num2; for(int i=0; i<size; i++){ ch = str.charAt(i); if(ch=='+' || ch=='-' || ch=='*' || ch=='/'){ num2=st.pop(); num1=st.pop(); if(ch=='+') st.push(num1+num2); else if(ch=='-') st.push(num1-num2); else if(ch=='*') st.push(num1*num2); else st.push(num1/num2); } else if('A'<=ch && ch <='Z') st.push(arr[ch-'A']); } System.out.print(String.format("%.2f",st.pop())); } } | cs |
'백준 1 > 자료구조' 카테고리의 다른 글
| [백준 2841] 외계인의 기타 연주 (C++/Java) (0) | 2020.12.06 |
|---|---|
| [백준 3986] 좋은 단어 (C++/Python) (0) | 2020.12.06 |
| [백준 1918] 후위 표기식 (C++/Java) (0) | 2020.12.06 |
| [백준 1874] 스택 수열 (C++/Python) (0) | 2020.12.06 |
| [백준 4949] 균형잡힌 세상 (C++/Python) (0) | 2020.12.06 |