Cod sursa(job #2217027)

Utilizator FlaviusFeteanFetean Flavius FlaviusFetean Data 28 iunie 2018 17:28:55
Problema Evaluarea unei expresii Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.52 kb
#include <fstream>
#include <stack>
#include <cstring>
#include <cstdlib>
#include <map>

using namespace std;
ifstream fin("expresie.in");
ofstream fout("expresie.out");

map<char,int> opOrd;
stack<int> nrStack;
stack<char> opStack;int k;
char exprPostfix[105000];

void pushParant() //reactioneaza la aparitia unei paranteze
{
    char nex[2] = " ";
    while(!opStack.empty() && opStack.top() != '(') k++,
        nex[0] = opStack.top(),strcat(exprPostfix, nex),opStack.pop();

    opStack.pop();
}

void pushSign(char opCrt) // reactioneaza la aparitia unui operator
{
    char nex[2] = " ";
    while(!opStack.empty() && opStack.top() != '(' && opOrd[opCrt] <= opOrd[opStack.top()])
        nex[0] = opStack.top(),strcat(exprPostfix, nex),opStack.pop(), k++;

    opStack.push(opCrt);
}

int nrCif(int x) {int ct = 0; while(x) x /= 10, ct++; return ct;}

int rezOp(char opCrt, int a, int b) // rezolva o operatie de baza(+\-\*\/)
{
    switch (opCrt){
        case '+': return a + b; case '-': return a - b;
        case '*': return a * b; case '/': return a / b;}
}


int main()
{
    char c, exprInfix[100002];
    int rez, i, f;

    opOrd['+'] = opOrd['-'] = 1, opOrd['*'] = opOrd['/'] = 2, opOrd['('] = 3;

    /// Scrierea ecuatiei in postfix -> o parcurgere
    fin.getline(exprInfix,100002);
    if(exprInfix[0] == '(') opStack.push('('), i = 1;else i = 0;

    while(exprInfix[i] != '\0')
    {
        if(isdigit(exprPostfix[k - 1])) exprPostfix[k++] = ',', exprPostfix[k] = '\0';

        while(isdigit(exprInfix[i]))
            exprPostfix[k++] = exprInfix[i++];


        while(exprInfix[i] != '\0' && !isdigit(exprInfix[i]))
        {
            if(exprInfix[i] == ')') pushParant(), i++;
            else pushSign(exprInfix[i]), i++;
        }
    }
    {char nex[2] = " ";
    while(!opStack.empty()) k++,nex[0] = opStack.top(),
        strcat(exprPostfix, nex),opStack.pop(); }


    /// Rezolvarea ecuatiei din postfix -> o parcurgere

    i = 0;

    while(exprPostfix[i] != '\0')
    {
        while(exprPostfix[i] != '\0' && exprPostfix[i] != ',' && isdigit(exprPostfix[i]))
        {
            nrStack.push(atoi(exprPostfix + i));
            i += nrCif(nrStack.top()); (!(exprPostfix[i] - ','))? i++ : i = i;
        }

        while(exprPostfix[i] != '\0' && !isdigit(exprPostfix[i]))
            f = nrStack.top(), nrStack.pop(),
            nrStack.top() = rezOp(exprPostfix[i++], nrStack.top(), f);
    }

    fout << nrStack.top();

    return 0;
}