Cod sursa(job #3340141)

Utilizator BidonTurtitBezdedan Eric BidonTurtit Data 12 februarie 2026 10:38:41
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.11 kb
#include <iostream>
#include <fstream>
#include <stack>
#include <map>
#include <vector>
#include <cstring>
#define Max 100005

using namespace std;

ifstream fin("evaluare.in");
ofstream fout("evaluare.out");

char s[Max];
vector <pair<int,char>> post;
map <char, int> order;
int eval()
{
    stack <int> nr;
    for(auto x: post)
    {
        if(x.second==0)
        {
            nr.push(x.first);
        }
        else
        {
            int a,b;
            a=nr.top();
            nr.pop();
            b=nr.top();
            nr.pop();
            if(x.second=='+')
                nr.push(a+b);
            else if(x.second=='-')
                nr.push(b-a);
            else if(x.second=='*')
                nr.push(a*b);
            else
                nr.push(b/a);
        }
    }
    return nr.top();
}

void intopost(char s[])
{
    stack <char> op;
    for(int i=0;s[i];i++)
    {
        if(isdigit(s[i]))
        {
            int t=0;
            while(isdigit(s[i]))
            {
                t=t*10+s[i]-'0';
                i++;
            }
            post.push_back({t,0});
            i--;
        }
        else
        {
            if(s[i]=='(')
            {
                op.push('(');
            }
            else if(s[i]==')')
            {
                while(op.top()!='(')
                {
                    post.push_back({0,op.top()});
                    op.pop();
                }
                op.pop();
            }
            else
            {
                while(!op.empty() &&  op.top()!='(' && order[s[i]]<=order[op.top()])
                {
                    post.push_back({0,op.top()});
                    op.pop();
                }
                op.push(s[i]);
            }
        }
    }
    while(!op.empty())
    {
        post.push_back({0,op.top()});
        op.pop();
    }
}

int main()
{
    fin>>s;
    order.insert({'*',2});
    order.insert({'/',2});
    order.insert({'+',1});
    order.insert({'-',1});
    intopost(s);
    fout<<eval();
    return 0;
}