Cod sursa(job #2255260)

Utilizator mihailarminia1234Arminia Mihail mihailarminia1234 Data 6 octombrie 2018 17:24:18
Problema Evaluarea unei expresii Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.61 kb
#include <bits/stdc++.h>

using namespace std;

stack <char> st;
stack <long long int> fin;
vector <string> sol;
vector <string> ::iterator it;
string in;
char input[100005];

int priority(char c)
{
    if (c == '+' || c == '-')
        return 1;

    if (c == '*' || c == '/')
        return 2;
}

void postfix(string str)
{
    string aux;

    for (int i = 0; i < str.size(); ++i)
    {
        aux = "";

        if (str[i] >= '0' && str[i] <= '9')
        {
            while (str[i] >= '0' && str[i] <= '9')
            {
                aux += str[i];
                ++i;
            }
            sol.push_back(aux);
            --i;
        }

        else if (str[i] == '(')
            st.push('(');

        else if (str[i] == ')')
        {
            while (st.top() != '(')
            {
                aux = st.top();
                sol.push_back(aux);
                st.pop();
            }

            st.pop();
        }

        else
        {
            if (st.empty() || st.top() == '(')
                    st.push(str[i]);
            else if (priority(str[i]) > priority(st.top()))
                    st.push(str[i]);
            else
            {
                aux = st.top();
                sol.push_back(aux);
                st.pop();
                st.push(str[i]);
            }
        }
    }

    while (!st.empty())
    {
        aux = st.top();
        sol.push_back(aux);
        st.pop();
    }
}

void solve()
{
    for (it = sol.begin(); it != sol.end(); ++it)
    {
        string aux = *it;

        if (aux[0] >= '0' && aux[0] <= '9')
        {
            long long int x = 0;

            for (int i = 0; i < aux.size(); ++i)
                x = x * 10 + (aux[i] - '0');

            fin.push(x);
        }
        else
        {
            long long int nr1, nr2, rez;
            nr1 = fin.top();
            fin.pop();
            nr2 = fin.top();
            fin.pop();

            if (aux[0] == '+')
                rez = 1LL * (nr1 + nr2);

            else if (aux[0] == '-')
                rez = 1LL * (nr2 - nr1);

            else if (aux[0] == '*')
                rez = 1LL * (nr1 * nr2);

            else if (aux[0] == '/')
                rez = 1LL * (nr2 / nr1);

            fin.push(rez);
        }
    }
}

int main()
{
    fgets (input, 100002, fopen("evaluare.in", "r"));

    for (int i = 0; i < strlen(input) - 1; ++i)
        in += input[i];

    postfix (in);
    solve();

    fprintf (fopen("evaluare.out", "w"), "%ld\n", fin.top());

    return 0;
}