ACPC OI 联赛 R4
T4 - 字符串表达式 题解
题面阅读
题目描述
给定一个字符串 ,代表一个算式(算式中可能包括 +,-,*,/,^,(,),数字),求运算后的结果 ,答案需要保留 位小数。
假定 ^ 的优先级大于 +,-,*,/ 的优先级。
输入格式
一行一个字符串 。
输出格式
表达式的结果 。
输入输出样例 #1
输入 #1
1+1输出 #1
2.000输入输出样例 #2
输入 #2
11-4*5+14+((11/(45-1)*4)*(0-11)/4+51/4)^(11/(45-1)*4))输出 #2
15.000说明/提示
对于 的数据,保证表达式 中没有 ^。
对于 的数据,保证表达式 中没有小数。
对于 的数据,保证表达式 中无空格,无负数,且 。
参考代码
#include <iostream>
#include <cmath>
#include <stack>
#include <sstream>
using namespace std;
#define int long long
int part(char op)
{
if (op == '^') return 3;
if (op == '*' || op == '/') return 2;
if (op == '+' || op == '-') return 1;
return 0;
}
double num(double b, double a, char op)
{
switch (op)
{
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/': return a / b;
case '^': return pow(a, b);
}
return 0;
}
double ans(string s)
{
stack<double> st;
stack<char> ops;
int i = 0;
while(i < s.size())
{
if(isdigit(s[i]))
{
double num = 0;
stringstream ss;
while (i < s.size() && (isdigit(s[i]) || s[i] == '.')) ss << s[i++];
ss >> num;
st.push(num);
}
else if (s[i] == '(') ops.push(s[i++]);
else if (s[i] == ')')
{
while (!ops.empty() && ops.top() != '(')
{
double b = st.top(); st.pop();
double a = st.top(); st.pop();
char op = ops.top(); ops.pop();
st.push(num(b, a, op));
}
if (!ops.empty()) ops.pop();
i++;
}
else
{
while (!ops.empty() && part(ops.top()) >= part(s[i]))
{
double b = st.top(); st.pop();
double a = st.top(); st.pop();
char op = ops.top(); ops.pop();
st.push(num(b, a, op));
}
ops.push(s[i++]);
}
}
while (!ops.empty())
{
double b = st.top(); st.pop();
double a = st.top(); st.pop();
char op = ops.top(); ops.pop();
st.push(num(b, a, op));
}
return st.top();
}
signed main()
{
string k;
cin >> k;
printf("%.3f", ans(k));
return 0;
}