题解:B4278 [蓝桥杯青少年组国赛 2023] 简单算术题
wangxiaochai · · 题解
感觉之前的题解写复杂了……
这题的算法标签是“栈”。但是按照栈先进后出的原则,没办法让公式从左到右计算,需要对栈进行转置才行。
那直接用“队列”不就好了?队列不就正好是先进先出嘛。因为涉及到对队尾和队首同时操作,所以本题选择用双向队列来存储数据。
剩下按照题意模拟一遍即可。因为乘法和除法是一样的优先级,加法和减法是一样的优先级,所以为了代码简洁,可以使用三元运算符。
#include <iostream>
#include <vector>
#include <deque>
using namespace std;
int x;
char c;
vector <char> op;
deque <int> q;
int main()
{
cin >> x;
q.push_back(x);
while (cin >> c >> x)
{
if (c=='*' || c=='/')
{
x = c=='*'? x*q.back() : q.back()/x;
q.pop_back();
q.push_back(x);
} else
{
op.emplace_back(c);
q.push_back(x);
}
}
x = q.front();
for (auto p : op)
{
q.pop_front();
x = p=='+'? x+q.front() : x-q.front();
}
cout << x;
return 0;
}