Cod sursa(job #2508204)

Utilizator andreigaliAndrei Galitianu andreigali Data 11 decembrie 2019 18:56:46
Problema Evaluarea unei expresii Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.71 kb
#include <iostream>
#include <fstream>
#include <cstring>
#include <stack>
#include <cstdlib>

using namespace std;

char a[100005];
stack<int> n;
stack<char> s;

int priority (char c)
{
    if(c=='(')
        return 0;
    if(c=='*' || c=='/')
        return 2;
    if(c=='+' || c=='-')
        return 1;
    return -1;
}

void solve()
{
    int a, b;
    a = n.top();
    n.pop();
    b = n.top();
    n.pop();

    if(s.top() == '+')
        n.push(a+b);
    if(s.top() == '-')
        n.push(b-a);
    if(s.top() == '*')
        n.push(a*b);
    if(s.top() == '/')
        n.push(b/a);
    ///cout << a << s.top() << b << "\n";
    s.pop();
}

int main()
{
    ifstream fin ("evaluare.in");
    ofstream fout("evaluare.out");
    fin.getline(a+1, 100005);
    a[0] = '(';
    int l = strlen(a);
    a[l] = ')';
    a[++l] = 0;

    for(int i=0; i<l; i++)
    {
        if(a[i] == '(')
        {
            s.push(a[i]);
        }
        if(a[i] == ')')
        {
            while(s.top()!='(')
                solve();
            s.pop();
        }
        if(a[i] >= '0' && a[i]<='9')
        {
            char nr[10];
            int l=0;
            while(a[i] >= '0' && a[i]<='9')
            {
                nr[l++] = a[i];
                i++;
            }
            nr[l] = 0;
            i--;
            int nnr = atoi(nr);
            n.push(nnr);
        }
        if(a[i] == '+' || a[i] == '-' || a[i] == '*' || a[i] == '/')
        {
            while( priority(s.top()) > priority(a[i]) )
            {
                solve();
            }
                s.push(a[i]);

        }
    }

    fout << n.top();

    return 0;
}