Cod sursa(job #2063581)

Utilizator 12FoarteAvem BAC 12Foarte Data 11 noiembrie 2017 12:11:35
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.63 kb
#include <fstream>
#include <stack>
#include <queue>
#include <string>
using namespace std;

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

char s[100005];
int i,n;
int nr;
stack <char> st;
stack <int> stn;
queue <string> fp;
string aux;

int prioritate(char o)
{
    switch(o)
    {
        case '+': return 1;
        case '-': return 1;
        case '*': return 2;
        case '/': return 2;
    }
    return 0;
}

void adaugaElement(char c)
{
    aux.clear();
    aux.push_back(c);
    fp.push(aux);
}

void operatie(char o)
{
    int x=stn.top(); stn.pop();
    int y=stn.top(); stn.pop();
    switch(o)
    {
        case '+': stn.push(x+y);break;
        case '-': stn.push(y-x);break;
        case '*': stn.push(x*y);break;
        case '/': stn.push(y/x);break;
    }
}

int main()
{
    f>>s;
    //toate parantezele devin rotunde
    for(i=0;s[i];++i)
        if(s[i]=='{' || s[i]=='[') s[i]='(';
        else if(s[i]=='}' || s[i]==']') s[i]=')';

    //adaug prima paranteza deschisa in stiva
    st.push('(');
    for(i=0;s[i];++i)
        if(s[i]=='(') st.push(s[i]); //paranteza
        else
            if(s[i]>='0' && s[i]<='9') //numar
            {
                aux.clear();
                while(s[i]>='0' && s[i]<='9')
                {
                    aux.push_back(s[i]);
                    i++;
                }
                fp.push(aux);
                --i;
            }
            else
                if(s[i]==')')
                {
                    while(st.top()!='(')
                    {
                        adaugaElement(st.top());
                        st.pop();
                    }
                    st.pop();
                }
                else //operator
                {
                    while(prioritate(st.top())>=prioritate(s[i]))
                    {
                        adaugaElement(st.top());
                        st.pop();
                    }
                    st.push(s[i]);
                }
    //sfarsit => extrag tot din stiva si pun in fp
    while(st.top()!='(')
    {
        adaugaElement(st.top());
        st.pop();
    }
    // calculul valorii expresiei

    while(!fp.empty())
    {
        aux=fp.front();
        if(aux[0]>='0' && aux[0]<='9')
        {
            //sir de caractere => numar
            nr=0;
            n=aux.length();
            for(i=0;i<n;++i) nr=nr*10+(aux[i]-'0');
            stn.push(nr);
        }
        else
            operatie(aux[0]);
        fp.pop();
    }

    g<<stn.top();

    f.close();g.close();
    return 0;
}