欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

理解计算过程中栈的作用:1356案例解析

最编程 2024-02-04 14:59:29
...

1356:计算(calc)

【题目描述】
小明在你的帮助下,破密了Ferrari设的密码门,正要往前走,突然又出现了一个密码门,门上有一个算式,其中只有“(”,“)”,“0-9”,“+”,“-”,“*”,“/”,“^”,求出的值就是密码。小明数学学得不好,还需你帮他的忙。(“/”用整数除法)

【输入】
共1行,为一个算式。

【输出】
共1行,就是密码。

【输入样例】
1+(3+2)(7^2+69)/(2)
【输出样例】
258

#include <bits/stdc++.h>
#define ll long long
#define inf 1<<30
#define PII pair<int,int>

using namespace std;
string s;
stack<int> s1;
stack<char> s2;

int level(char c)
{
    if(c=='+'||c=='-')
        return 1;
    if(c=='*'||c=='/')
        return 2;
    if(c=='^')
        return 3;
    return 0;//左右括号最低
}
void cal()
{
    int y=s1.top();
    s1.pop();
    int x=s1.top();
    s1.pop();
    char c=s2.top();
    s2.pop();
    switch(c)
    {
        case '+':s1.push(x+y);break;
        case '-':s1.push(x-y);break;
        case '*':s1.push(x*y);break;
        case '/':s1.push(x/y);break;
        case '^':s1.push(pow(x,y));break;
    }
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cin >> s;
    int n=s.size(),t=0,flag=0;
    for(int i=0;i<n;i++)
    {
        if(isdigit(s[i]))
        {
            t=t*10+s[i]-'0';
            flag=1;
        }
        else
        {
            if(flag)
                s1.push(t),flag=t=0;
            if(s[i]=='(')//优先级最低
            {
                s2.push('(');
                continue;
            }
            if(s[i]==')')//优先级最低
            {
                while(s2.top()!='(')
                    cal();//多次运算
                s2.pop();
                continue;
            }
            while(!s2.empty()&&level(s2.top())>=level(s[i]))//还有运算符
                cal();
            s2.push(s[i]);
        }
    }
    if(flag)
        s1.push(t);
    while(!s2.empty())
        cal();
    cout << s1.top() << endl;
    return 0;
}

推荐阅读