蓝桥杯 算法训练 表达式计算

算法训练 表达式计算
时间限制:1.0s 内存限制:256.0MB
提交此题
问题描述
  输入一个只包含加减乖除和括号的合法表达式,求表达式的值。其中除表示整除。
输入格式
  输入一行,包含一个表达式。
输出格式
  输出这个表达式的值。
样例输入
1-2+3*(4-5)
样例输出
-4
数据规模和约定
  表达式长度不超过100,表达式运算合法且运算过程都在int内进行。

#include
using namespace std;
stack<string> s1;//最后存储逆波兰顺序栈
stack<string > s2;//先存的是逆波兰倒序栈
stack<int > s3;//数字栈
map<string ,int > d;
string s;
void runin(string c)
{
    //cout<
    if(d[c]>d[s1.top()]) s1.push(c);
    else if(c=="(") s1.push("!");
    else if(c==")")
    {
        while(s1.top()!="!")
        {
            s2.push(s1.top());
            s1.pop();
        }
        s1.pop();
    }
    else
    {
        s2.push(s1.top());
        s1.pop();
        s1.push(c);
    }
    //cout<
}
int main()
{
    d["#"] = 0;
    d["+"] = 1;
    d["-"] = 1;
    d["*"] = 2;
    d["/"] = 2;
    while(cin>>s)
    {
        s1.push("#");
        string de;
        for(int i=0;s[i];)
        {
            //cout<
            if(s[i]>='0'&&s[i]<='9')
            {
                while(s[i]>='0'&&s[i]<='9')
                    de+=s[i++];
                s2.push(de);
                de.clear();
            }
            if(!(s[i]>='0'&&s[i]<='9'))
            {
                string tt;
                tt+=s[i];
                //cout<
                runin(tt);
                tt.clear();
            }
            i++;
        }

        while(s1.size()&&s1.top()!="#")
        {
            //cout<
            s2.push(s1.top());
            s1.pop();
        }
        s1.pop();
        while(s2.size())
        {
            //cout<
            s1.push(s2.top());
            s2.pop();
        }
        while(s1.size())
        {
            if(d[s1.top()])
            {
                int l=s3.top();s3.pop();
                int r=s3.top();s3.pop();
               // cout<
                if(s1.top()=="+") s3.push(l+r);
                if(s1.top()=="-") s3.push(r-l);
                if(s1.top()=="*") s3.push(l*r);
                if(s1.top()=="/") s3.push(r/l);
            }
            else
            {
                de=s1.top();
                int xx=0;
                for(int i=0;de[i];i++)
                {
                    xx=xx*10+de[i]-'0';
                }
                s3.push(xx);
            }
            s1.pop();
        }
        //cout<
        cout<

你可能感兴趣的:(蓝桥杯)