Cod sursa(job #2375302)

Utilizator AlexandruGabrielAliciuc Alexandru AlexandruGabriel Data 8 martie 2019 00:33:50
Problema Evaluarea unei expresii Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.75 kb
#include <bits/stdc++.h>
#define mod 1000000000

using namespace std;

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

int len;
char expr[100005], fp[300005];
stack <char> op;
stack <long long> st;

//forma poloneza postfixata
void Transforma()
{
    for (int i = 0; i < strlen(expr); i++)
    {
        if (isdigit(expr[i]))
        {
            while (isdigit(expr[i]))
            {
                fp[len++] = expr[i];
                i++;
            }
            i--;
            fp[len++] = ',';
        }
        else if (expr[i] == '*' || expr[i] == '/')
        {
            if (!op.empty() && (op.top() == '*' || op.top() == '/'))
            {
                fp[len++] = op.top();
                op.pop();
            }
            op.push(expr[i]);
        }
        else if (expr[i] == '+' || expr[i] == '-')
        {
            while (!op.empty())
            {
                if (op.top() == '*' || op.top() == '/')
                {
                    fp[len++] = op.top();
                    op.pop();
                }
                else break;
            }
            if (!op.empty() && (op.top() == '+' || op.top() == '-'))
            {
                fp[len++] = op.top();
                op.pop();
            }
            op.push(expr[i]);
        }
        else if (expr[i] == '(')
            op.push(expr[i]);
        else if (expr[i] == ')')
        {
            while (!op.empty())
            {
                if (op.top() != '(')
                {
                    fp[len++] = op.top();
                    op.pop();
                }
                else
                {
                    op.pop();
                    break;
                }
            }
        }
    }
    while (!op.empty())
    {
        fp[len++] = op.top();
        op.pop();
    }
}

void Rezolva()
{
    for (int i = 0; i < len; i++)
    {
        if (isdigit(fp[i]))
        {
            long long nr = 0;
            while (isdigit(fp[i]))
            {
                nr = nr * 10 + (fp[i] - '0');
                i++;
            }
            nr %= mod;
            st.push(nr);
        }
        else
        {
            long long top = st.top();
            st.pop();
            if (fp[i] == '+')
                st.top() = (st.top() + top) % mod;
            else if (fp[i] == '-')
                st.top() = (st.top() - top + mod) % mod;
            else if (fp[i] == '*')
                st.top() = (st.top() * top) % mod;
            else if (fp[i] == '/')
                st.top() = (st.top() / top) % mod;
        }
    }
    fout << st.top() % mod;
}

int main()
{
    fin >> expr;
    Transforma();
    Rezolva();
    return 0;
}