Cod sursa(job #2342200)

Utilizator Cezar211Popoveniuc Cezar Cezar211 Data 12 februarie 2019 17:39:21
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.24 kb
#include <bits/stdc++.h>
#define NM 100005
using namespace std;
ifstream fin ("evaluare.in");
ofstream fout ("evaluare.out");
///-1 +
///-2 -
///-3 *
///-4 /
vector<int> num;
int operatie(int a, int b, int nr)
{
    if(nr == -1)
        return a+b;
    else if(nr == -2)
        return a-b;
    else if(nr == -3)
        return a*b;
    else return a/b;
}
void pusare(char s)
{
    if(s == '+')
        num.push_back(-1);
    else if(s == '-')
        num.push_back(-2);
    else if(s == '*')
        num.push_back(-3);
    else num.push_back(-4);
}
bool better_operator(char x, char y)
{
    int nr1, nr2;
    if(x == '+' || x == '-')
        nr1 = 1;
    else nr1 = 2;
    if(y == '+' || y == '-')
        nr2 = 1;
    else nr2 = 2;
    if(nr1>=nr2)
        return 1;
    return 0;
}
char c[NM];
stack<char> s;
int main()
{
    fin.getline(c, NM);
    int n = strlen(c);
    for(int i=0; i<n; i++)
    {
        if(isdigit(c[i]))
        {
            int j, nr = 0;
            for(j=i; isdigit(c[j]); j++)
                nr = nr*10 + c[j] - '0';
            i = j-1;
            num.push_back(nr);
        }
        else if(c[i] == '(')
                s.push('(');
        else if(c[i] == '+' || c[i] == '-' || c[i] == '*' || c[i] == '/')
        {
            while(!s.empty() && s.top()!='(')
            {
                if(better_operator(s.top(), c[i]))
                {
                    pusare(s.top());
                    s.pop();
                }
                else break;
            }
            s.push(c[i]);
        }
        else if(c[i] == ')')
        {
            while(!s.empty() && s.top()!='(')
            {
                pusare(s.top());
                s.pop();
            }
            s.pop();
        }
    }
    while(!s.empty())
    {
        pusare(s.top());
        s.pop();
    }
    stack<int> rez;
    for(int i=0; i<num.size(); i++)
    {
        if(num[i] >= 0)
            rez.push(num[i]);
        else
        {
            int nr1 = rez.top();
            rez.pop();
            int nr2 = rez.top();
            rez.pop();
            rez.push(operatie(nr2, nr1, num[i]));
        }
    }
    fout << rez.top();
    return 0;
}