Cod sursa(job #2973704)

Utilizator Luca_CristianZamfir Luca-Cristian Luca_Cristian Data 1 februarie 2023 17:32:28
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.47 kb
#include <fstream>
#include <vector>
#include <stack>

using namespace std;

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

vector <char> tokens;
stack <int> val;
stack <char> op;
void parsing()
{
    char ch;
    fin.get(ch);
    while(ch != '\n')
    {
        tokens.push_back(ch);
        fin.get(ch);
    }
}
int prioritate(char ch)
{
    if(ch == '*' || ch == '/')
        return 2;
    else if(ch == '+' || ch == '-')
        return 1;
    return 0;
}
int operatie(int a, int b, char semn)
{
    switch(semn)
    {
    case '+':
        return a + b;
    case '-':
        return a - b;
    case '*':
        return a * b;
    case '/':
        return a / b;
    }
}
void numer_parsing(int &i)
{
    int ans = 0;
    while(i < tokens.size() && isdigit(tokens[i]))
    {
        ans = ans * 10 + tokens[i] - '0';
        i++;
    }
    --i;
    val.push(ans);
}


void solve()
{
    int i;
    for(i = 0; i < tokens.size(); i++)
    {
        if(tokens[i] == '(')
            op.push('(');
        else if(isdigit(tokens[i]))
            numer_parsing(i);
        else if(tokens[i] == ')')
        {
            while(!op.empty() && op.top() != '(')
            {
                int val2 = val.top();
                val.pop();
                int val1 = val.top();
                val.pop();
                char semn = op.top();
                op.pop();

                val.push(operatie(val1, val2, semn));
            }
            if(!op.empty())
                op.pop();
        }
        else
        {
            while(!op.empty() && prioritate(op.top()) >= prioritate(tokens[i]))
            {
                int val2 = val.top();
                val.pop();
                int val1 = val.top();
                val.pop();
                char semn = op.top();
                op.pop();

                val.push(operatie(val1, val2, semn));
            }
            op.push(tokens[i]);
        }
    }
     while(!op.empty())
     {
            int val2 = val.top();
            val.pop();
            int val1 = val.top();
            val.pop();
            char semn = op.top();
            op.pop();

            val.push(operatie(val1, val2, semn));
     }
    fout << val.top() << '\n';
}



int main()
{
    parsing();
    /*vector <char>:: iterator it = tokens.begin();
    for(; it != tokens.end(); it++)
        fout << *it << " ";*/
    solve();

    return 0;
}