Cod sursa(job #3216123)

Utilizator uncle_sam_007IOAN BULICA uncle_sam_007 Data 15 martie 2024 17:33:06
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.55 kb
#include <iostream>
#include <fstream>
#include <cstring>
#include <cctype>
#include <stack>

using namespace std;

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

char s[100001];
stack<char> op, polo;
stack <int>r;

int pr(char ch)
{
    switch(ch)
    {
    case '+':
        return 1;
    case '-':
        return 1;
    case '*':
        return 2;
    case '/':
        return 2;
    case '%':
        return 2;
    }
    return 0;
}
int operatie(int a, int b, char op)
{
    switch(op)
    {
    case '+':
        return b + a;
    case '-':
        return b - a;
    case '*':
        return b * a;
    case '/':
        return b / a;
    default:
        return -1;
    }
}

int main()
{
    int n, i,a,b;
    char ch;

    fin.getline(s, 100001);
    n = strlen(s);

    for(i = 0; i < n; ++i)
    {
        if(isdigit(s[i]))
        {
            while(isdigit(s[i]))
            {
                polo.push(s[i]);
                i++;
            }
            polo.push(' ');
            i--;
            continue;
        }
        if(s[i] == '(')
        {
            op.push(s[i]);
            continue;
        }
        if(s[i] == ')')
        {
            while(!op.empty() && op.top() != '(')
            {
                ch = op.top();
                polo.push(ch);
                op.pop();
            }
            op.pop();
            continue;
        }
        if(op.empty() || op.top() == '(' || pr(s[i]) > pr(op.top()))
            op.push(s[i]);
        else
        {
            while(!op.empty() && pr(s[i]) <= pr(op.top()))
            {
                ch = op.top();
                polo.push(ch);
                op.pop();
            }
            op.push(s[i]);
        }
    }
    while(!op.empty())
    {
        polo.push(op.top());
        op.pop();
    }

    while(!polo.empty())
    {
        op.push(polo.top());
        polo.pop();
    }
    int num = 0;
    while(!op.empty())
    {
        if(isdigit(op.top()))
        {
            num *= 10;
            num += op.top() - '0';
            op.pop();
        }
        else if(op.top() == ' ')
        {
            r.push(num);
            num = 0;
            op.pop();
        }
        else
        {
            a = r.top();
            r.pop();
            b = r.top();
            r.pop();
            r.push(operatie(a, b, op.top()));
            op.pop();
        }
    }

    fout << r.top();
    fin.close();
    fout.close();
    return 0;
}