※ 글쓴이는 취미로 코딩을 익혀보는 사람이라 정확하지 않은 내용을 담고 있을 수 있다 ※
이번에 볼 문제는 백준 3284번 문제인 MASS이다.
문제는 아래 링크를 확인하자.
https://www.acmicpc.net/problem/3284
3284번: MASS
The first and only line of input file contains a formula of a molecule whose mass needs to be determined. A formula of a molecule will consist of characters H, C, O, (, ) , 2, 3, ..., 9 only. Its length will be less or equal to 100 characters.
www.acmicpc.net
각 괄호가 닫힐 때마다 대응되는 괄호쌍 안에 담긴 물질의 질량을 합쳐 하나의 값으로 바꿔주고, 한자리 수를 입력받을 때마다 바로 직전에 작업한 값에 곱해 해당 한자리 수를 곱해나가며 문제를 해결하자.
괄호의 순서를 관리하는 것은 스택 자료구조를 이용하면 편하게 해낼 수 있다.
아래는 제출한 소스코드이다.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
string s;
vector<int> stk;
int ans;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cin >> s;
for (auto& l : s) {
if (l == 'H') stk.emplace_back(1);
else if (l == 'C') stk.emplace_back(12);
else if (l == 'O') stk.emplace_back(16);
else if (l == '(') stk.emplace_back(-1);
else if (l == ')') {
int tmp = 0;
while (stk.back() > -1) {
tmp += stk.back();
stk.pop_back();
}
stk.pop_back();
stk.emplace_back(tmp);
}
else stk.back() *= l - '0';
}
while (!stk.empty()) {
ans += stk.back();
stk.pop_back();
}
cout << ans;
}
728x90
'BOJ' 카테고리의 다른 글
[BOJ 2079 // C++] 팰린드롬 (1) | 2023.08.27 |
---|---|
[BOJ 3279 // C++] DOLLARS (0) | 2023.08.26 |
[BOJ 3283 // C++] BARCODE (0) | 2023.08.24 |
[BOJ 1799 // C++] 비숍 (0) | 2023.08.23 |
[BOJ 2546 // C++] 경제학과 정원영 (0) | 2023.08.22 |