ccf csp 201903-2 二十四点
题目图片:
利用两个栈保存数字和符号,其实这题挺简单的,写的有点复杂了。
遇到+号或者-号直接将栈中的进行计算,遇到x或/先将符号和后面一位数入栈,再计算。
#include <iostream>
#include <string>
#include <stack>
using namespace std;
void cal(stack<int> &m, stack<char> &n)//计算函数
{
int a = m.top();
m.pop();
int b = m.top();
m.pop();
switch (n.top()){
case '+':
m.push(a + b);
break;
case '-':
m.push(b - a);
break;
case 'x':
m.push(b*a);
break;
case '/':
m.push(b / a);
break;
}
n.pop();
}
int main()
{
int t;
cin >> t;
string s;
while(t--){
stack<int> m;
stack<char> n;
cin >> s;
for (int i = 0; i < 7;)
{
if (s[i] >= '0' && s[i] <= '9'){
m.push(s[i] - '0');
i++;
}
else{
switch (s[i]){
case '+'://+,-直接计算
case '-':
if (!n.empty())
cal(m, n);
n.push(s[i]);
i++;
break;
case 'x'://x,/入栈再算
case '/':
n.push(s[i]);
m.push(s[i + 1] - '0');
cal(m,n);
i += 2;
break;
}
}
}
while (!n.empty())
cal(m, n);
if(m.top() == 24)
cout << "Yes" << endl;
else
cout << "No" << endl;
}
return 0;
}