Cod sursa(job #2946858)

Utilizator NutaAlexandruASN49K NutaAlexandru Data 25 noiembrie 2022 11:06:09
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.73 kb
#include <fstream>
#include<vector>
#include <algorithm>
#import <cmath>
#import <cassert>
#import <queue>
#import <map>
#import <stack>
using namespace std;
namespace EXP
{
    int cod(char ch)
    {
        if(ch=='/')return 2;
        if(ch=='*')return 2;
        if(ch=='-' || ch=='+')return 1;
        return 0;
    }
    int aplic(int a,int b,char c)
    {
        if(c=='+')return a+b;
        if(c=='-')return a-b;
        if(c=='/')return a/b;
        return a*b;
    }
    stack<int>val;
    stack<char>op;
    void calc()
    {
        int v2=val.top();
        val.pop();
        int v1=val.top();
        val.pop();
        char o=op.top();
        op.pop();
        val.push(aplic(v1,v2,o));
    }
    int solve(string s)
    {
        s="("+s+")";
        int n=(int)s.size();
        for(int i=0; i<n; i++)
        {
            if(s[i]==' ')continue;
            if(s[i]=='(')
            {
                op.push(s[i]);
                continue;
            }
            else if(s[i]==')')
            {
                while(op.top()!='(')calc();
                op.pop();
            }
            else if(isdigit(s[i]))
            {
                int x=0;
                while(isdigit(s[i]))
                {
                    x=x*10+(s[i])-'0';
                    i++;
                }
                val.push(x);
                i--;
            }
            else
            {
                while(cod(s[i])<=cod(op.top()))calc();
                op.push(s[i]);
            }
        }
        return val.top();

    }
}
main()
{
    ifstream cin("evaluare.in");
    ofstream cout("evaluare.out");
    string s;
    cin>>s;
    cout<<EXP::solve(s);

}