Cod sursa(job #1977809)

Utilizator robert_velisculfv@yahoo.comVeliscu Robert-Valentin [email protected] Data 6 mai 2017 11:02:05
Problema Evaluarea unei expresii Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 2.62 kb
#include <fstream>
#include <stack>
#include <cstring>

using namespace std;

ifstream f("evaluare.in");
ofstream g("evaluare.out");

bool ok,l;
long long n, u, y, v[100003], x, rez[100003];
char c, fp[100003], a;
stack <char> st;

int val(char op)
{
    if(strchr("*/", op))
        return 1;
    else
        if(strchr("+-", op))
            return 2;
        else
            return 3;
}

long long r(int a, int b, char c)
{
    if(c == '+')
        return a+b;
    else
    {
        if(c == '-')
            return a-b;
        else
            {
                if(c == '*')
                    return a*b;
                else return a/b;
            }
    }
}

int main()
{
    while( f >> c )
    {
        if(strchr("+-*/()", c))
        {
            l = 0;
            if(st.size() && c != ')')
            {
                a = st.top();
                ok = 0;
                if(val(a) <= val(c) && c!='(' )
                {
                    st.pop();
                    fp[++u] = a;
                    ok = 1;
                    while(ok && st.size())
                    {
                        ok = 0;
                        a = st.top();
                        if(val(a) >= val(c))
                         {
                             st.pop();
                             fp[++u] = a;
                             ok = 1;
                         }
                    }
                }
                st.push(c);
            }
            else
                if(c == ')')
                {
                    a = st.top();
                    while( a != '(' )
                    {
                        st.pop();
                        fp[++u] = a;
                        a = st.top();
                    }
                    st.pop();
                }
            else
                st.push(c);
        }
        else
        {
            x = c - '0';
            if(l == 0)
            {
                v[++u] = x;
                l = 1;
                fp[u] = 'a';
            }
            else
            {
                v[u] *= 10;
                v[u] += x;
            }
        }
    }

    while(st.size())
    {
        fp[++u] = st.top();
        st.pop();
    }
    rez[1] = v[1];
    n = 1;
    for(int i = 2; i <= u; i++ )
    {
        if( fp[i] != 'a' )
        {
            x = rez[n-1];
            y = rez[n];
            rez[n] = 0;
            n--;
            rez[n] = r(x,y,fp[i]);
        }
        else
            rez[++n] = v[i];
    }

    g<<rez[1];

    return 0;
}