Cod sursa(job #1408153)

Utilizator cypry97Dascalitei Ciprian cypry97 Data 29 martie 2015 20:52:31
Problema Evaluarea unei expresii Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 2.79 kb
#include <iostream>
#include <fstream>
#include <string>
#include <stack>
using namespace std;

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

struct elem
{
    long long rez,p,nr;
    char op1,op2;
    bool op;
    elem():
        rez(0),p(1),nr(0),op1('+'),op2('*'),op(false)
    {
    }
};

string expr;
stack < elem > st;
long long rez;

void citire()
{
    expr.reserve(100008);
    getline(in,expr);
    in.close();
}

void evaluare()
{
    volatile char c2;
    volatile long long nr2;

    expr += '+';
    long long x;
    st.push(elem());
    //10 + 20 * 30
    for(auto c = expr.begin(); c != expr.end(); c++)
    {
        c2=*c;
        if(*c == '+' || *c=='-')
        {
            if(st.top().op==0)
            {
                if(st.top().op1=='+')
                    st.top().rez+=st.top().nr;
                else
                    st.top().rez-=st.top().nr;
            }
            else
            {
                if(st.top().op2=='*')
                    st.top().p*=st.top().nr;
                else
                    st.top().p/=st.top().nr;
                if(st.top().op1 == '+')
                    st.top().rez+=st.top().p;
                else
                    st.top().rez-=st.top().p;
            }
            st.top().op=0;
            st.top().op1=*c;

        }
        else if(*c == '*' || *c == '/')
        {
            if(st.top().op==0)
            {
                st.top().p=st.top().nr;
                st.top().op=1;
            }
            else
            {
                if(st.top().op2=='*')
                    st.top().p*=st.top().nr;
                else
                    st.top().p/=st.top().nr;
            }
            st.top().op2=*c;
        }
        else if (*c == ')')
        {
            if(st.top().op==1)
                if(st.top().op2=='*')
                    st.top().p*=st.top().nr;
                else
                    st.top().p/=st.top().nr;

            if(st.top().op1=='+')
                st.top().rez+=st.top().p;
            else
                st.top().rez-=st.top().p;
            x=st.top().rez;
            st.pop();
            st.top().nr=x;
        }
        else if(*c == '(')
            st.push(elem());
        else
        {
            st.top().nr=(*c-'0');
            c++;
            while(*c>='0' && *c<='9')
            {
                st.top().nr*=10;
                st.top().nr+=(*c-'0');
                c++;
            }
            c--;
            nr2=st.top().nr;
        }
        //cout<<st.size()<<' '<<st.top().rez<<' '<<st.top().p<<'\n';
    }
    rez=st.top().rez;
}

void afisare()
{
    out<<rez;
}

int main()
{
    citire();
    evaluare();
    afisare();
    return 0;
}