Cod sursa(job #2169525)

Utilizator SahMatCodrea Andrei SahMat Data 14 martie 2018 15:58:52
Problema Evaluarea unei expresii Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 2.3 kb
#include <fstream>
#include <cstring>
#include <stack>
using namespace std;
ifstream fi("evaluare.in");
ofstream fo("evaluare.out");

char a[100001];
char b[100001];
char res[200005];
int k=-1;
bool operand(char exp)
{
    if(exp>='0' and exp<='9')
    return 1;
    return 0;
}
bool operator_(char exp)
{
    if(exp=='+' or exp=='-' or exp=='*' or exp=='/')
        return 1;
    return 0;
}
bool priority(char a, char exp)
{
    if((exp=='+' or exp=='-') and (a=='*' or a=='/'))
        return 1;
    return 0;
}

void infix_postfix(char exp[100001])
{
    stack <char> s;

    for(int i=0;i<strlen(exp);i++)
    {
        if(operand(exp[i]))
        {

            while(exp[i]>='0' and exp[i]<='9')
            {
                res[++k]=exp[i];
                i++;
            }
            res[++k]=' ';
            i--;
        }
        else if(operator_(exp[i]))
        {
            while(!s.empty() and s.top()!='(' and priority(s.top(),exp[i]))
            {
             res[++k]=s.top();
             s.pop();
            }
            s.push(exp[i]);
        }
        else if(exp[i]=='(')
            s.push(exp[i]);
        else if(exp[i]==')')
        {
            while(s.top()!='(')
            {
                res[++k]=s.top();
                s.pop();
            }
            s.pop();
        }

    }
    while(!s.empty())
    {
        res[++k]=s.top();
        s.pop();

    }

}

void evaluation()
{
    stack <int> s;
    int op;
    for(int i=0;i<strlen(res);i++)
    {
        op=0;
        if(operand(res[i]))
        {
            while(operand(res[i]))
            {
                op=op*10+(res[i]-'0');
                i++;
            }
            i--;
            s.push(op);
        }
        else if(operator_(res[i]))
        {
            int b=s.top();
            s.pop();
            int a=s.top();
            s.pop();
            if(res[i]=='+')
                s.push(a+b);
            if(res[i]=='-')
                s.push(a-b);
            if(res[i]=='*')
                s.push(a*b);
            if(res[i]=='/')
                s.push(a/b);

        }
    }
    fo<<s.top();
}

int main()
{
    fi.getline(a,100001);

    infix_postfix(a);
    evaluation();


    return 0;
}