[백준] 2257번 : 화학식량

김개발·2021년 11월 3일
0

백준

목록 보기
68/75

문제 푼 날짜 : 2021-11-02

문제

문제 링크 : https://www.acmicpc.net/problem/2257

접근 및 풀이

stack을 이용하면 쉽게 풀 수 있는 문제였다.
원소 기호가 뜻하는 숫자가 다르기 때문에 stack의 타입을 어떻게 해야할지 고민하다가 string을 이용하여 해결할 수 있었다.

코드

#include <bits/stdc++.h>

using namespace std;

int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);
    
    string expr = "";
    cin >> expr;
    stack<string> st;
    
    for (char c : expr) {
        string s = "";
        s += c;
        if (s == "(" || s == "H" || s == "C" || s == "O") {
            st.push(s);
        } else if (s == ")") {
            int num = 0;
            while (!st.empty() && st.top() != "(") {
                if (st.top() == "H") {
                    num += 1;
                } else if (st.top() == "C") {
                    num += 12;
                } else if (st.top() == "O") {
                    num += 16;
                } else {
                    num += stoi(st.top());
                }
                st.pop();
            }
            st.pop();
            st.push(to_string(num));
        } else if (s >= "1" && s <= "9") {
            int tmp = 0;
            if (st.top() == "H") {
                tmp = 1;
            } else if (st.top() == "C") {
                tmp = 12;
            } else if (st.top() == "O") {
                tmp = 16;
            } else {
                tmp = stoi(st.top());
            }
            st.pop();
            st.push(to_string(tmp * stoi(s)));
        }
    }
    
    int sum = 0;
    while (!st.empty()) {
        if (st.top() == "H") {
            sum += 1;
        } else if (st.top() == "C") {
            sum += 12;
        } else if (st.top() == "O") {
            sum += 16;
        } else {
            sum += stoi(st.top());
        }
        st.pop();
    }
    cout << sum;
    return 0;
}

결과

피드백

기본기에 더욱 집중하자.

profile
개발을 잘하고 싶은 사람

0개의 댓글