問題
https://onlinejudge.u-aizu.ac.jp/courses/lesson/1/ALDS1/3/ALDS1_3_A (新しいタブで開く)
問題文
逆ポーランド記法で与えられた数式の計算結果を出力してね。
制約
- オペランド数
- 演算子数
- 演算子は
+
,-
,*
のみ - オペランドは 以下の正の整数
- 計算途中の値
サンプル
I/O 1
1 2 +
3
I/O 2
1 2 + 3 4 - *
-3
考察
stack
に積んでいって、演算子が出てきたら pop
して計算して push
するだけ。
コード
int main() {
string s;
getline(cin, s);
int n = s.size();
queue<string> q;
{
string tmp = "";
rep(i, n) {
if (s[i] == ' ') {
q.push(tmp);
tmp = "";
}
else
tmp.push_back(s[i]);
}
q.push(tmp);
}
stack<double> st;
while (!q.empty()) {
string tmp = q.front();
q.pop();
if (tmp == "+" || tmp == "-" || tmp == "*") {
double b = st.top();
st.pop();
double a = st.top();
st.pop();
if (tmp == "+") st.push(a + b);
else if (tmp == "-")
st.push(a - b);
else if (tmp == "*")
st.push(a * b);
}
else
st.push(stoi(tmp));
}
cout << st.top() << endl;
return 0;
}