题目思路
先将它转换为后缀表达式,再求值。
但是转换过程中可能有多余括号,那我们就要把它删去。
用栈,左括号进栈后,之后对应一个右括号。如果多余,就出栈。
中缀转后缀方法:
定义一个栈。 输入原算式。
如果是数字,直接加入后缀表达式。 如果检测到字符: 如果为左括号,直接进栈。 若为右括号,依次将栈中的符号出栈后缀表达式,直到遇到 左括号,就将左括号出栈,然后停止。 如果比栈顶运算符的优先级高,或者栈顶元素为左括号,直接进栈。 否则,依次弹出栈顶元素加入后缀表达式,直到遇到比它优先级高的元素,或者遇到左括号。 如果最后还剩下东西在栈里,直接出栈加到后缀表达式里。
做完之后就是正常的了,求值方法:P1449 后缀表达式
AC CODE
#include <bits/stdc++.h>
using namespace std;
#define ll long long
stack <ll> s;
string str,ans,ss;
ll p[130],k,len;
int main()
{
p['+']=1;
p['-']=1;
p['*']=2;
p['/']=2;
p['^']=3;
cin>>str;
str='(' + str + ')';//为了避开一些边界的情况
for(int i=0;i<str.length();i++)
{
if(str[i]=='(') s.push(i);
else if(str[i]==')')
{
if(s.empty())
{
str.erase(i,1);
i--;
}
else s.pop();
}
}
while(!s.empty())
{
str.erase(s.top(),1);//从后往前删,不影响下标
s.pop();
}
for(int i=0;i<str.length();i++)
if(str[i]=='('&&str[i+1]=='-') str.insert(i+1,"0");
//cout << str <<endl;
for(int i=0;i<str.length();i++)
{
if(str[i]<='9'&&str[i]>='0')
{
ans+=str[i];
if(!(str[i+1]<='9' && str[i+1]>='0')) ans+='.';
}
else if(str[i]=='(' ) s.push('(');
else if(str[i]==')' )
{
while(s.top() != '(')
{
ans+=s.top();
s.pop();
}
s.pop();//将左括号出栈
}
else
{
while(!s.empty()&&p[s.top()]>=p[str[i]])
{
ans+=s.top();
s.pop();
}
s.push(str[i]);
}
}
while(!s.empty())
{
ans+=s.top();
s.pop();
}
str=ans;
for( int i=0;i<str.length();i++)
{
if(str[i]>='0' && str[i]<='9') k=k*10+str[i]-'0';
else if(str[i]=='.')
{
s.push(k);
k=0;
}
else
{
ll a,b;
b=s.top();s.pop();a=s.top();s.pop();
if(str[i] == '+') s.push(a+b);
if(str[i] == '-') s.push(a-b);
if(str[i] == '*') s.push(a*b);
if(str[i] == '/') s.push(a/b);
if(str[i] == '^') s.push(pow(a,b));
}
}
cout<<s.top()<<endl;
return 0;
}