Cod sursa(job #2315506)

Utilizator DianaIfrosaIfrosa Diana DianaIfrosa Data 10 ianuarie 2019 01:00:04
Problema Evaluarea unei expresii Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.46 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");

char ex[100005];
bool vec[100005];
stack <int> S;//calcul final
stack <char> st; //stiva cu operatori
char fp[100005]; //forma poloneza
int lg,poz;
void Forma()
{   char op; int nr;
    for(int i=0;i<lg;i++)
    {
        if(isdigit(ex[i]))
         {   nr=0;
             while(isdigit(ex[i])) // form numar
             {nr=nr*10+ex[i]-'0';i++;}
             i--; //de la for

             fp[poz++]=nr;
         } //operand
        else //operator
            if(!st.empty())
            { st.push(ex[i]);// pun op
              op=st.top(); //st.pop();
              if(op=='*' || op=='/') ///prior 1
                  {   st.pop();
                      if(st.top()=='*' || st.top()=='/') ///prior 1
               {fp[poz]=st.top();
                vec[poz]=1; poz++; st.pop();
                  st.push(op);
               }
                else st.push(op);
                  }
             else if(op=='+' || op=='-') ///prior 2
             {st.pop();
             if(st.top()=='*' || st.top()=='/' || st.top()=='-' ||st.top()=='+') ///prior 1 sau 2
               {fp[poz]=st.top(); vec[poz]=1; poz++; st.pop();
                  st.push(op);
                  //fout<<poz;
               }
               else st.push(op);
             }
             else if(op==')')
             {
                 st.pop();
                 while(st.top()!='(')
                        {fp[poz]=st.top(); vec[poz]=1; poz++; st.pop();}
                 st.pop(); //parant deschisa
             }


             }
             else st.push(ex[i]);




    }
    while(!st.empty())  //mut restul
    {
        fp[poz]=st.top(); vec[poz]=1; poz++; st.pop();
    }
}
void Af()
{   //fout<<fp[0]<<"\n";
    for(int i=0;i<poz;i++)
    fout<<vec[i]<<" ";
}
void Calcul()
{   char op; int nr1,nr2;
    for(int i=0;i<poz;i++)
    if(vec[i]==0) //nu e semn
      {
           S.push(int(fp[i]));
      }
    else
    {
        op=fp[i];
        nr1=S.top();S.pop();
        nr2=S.top(); S.pop();
        if(op=='+') S.push(nr1+nr2);
        else if(op=='-') S.push(nr2-nr1);
        else if(op=='*') S.push(nr1*nr2);
        else if(op=='/') S.push(nr2/nr1);

    }

    fout<<S.top(); //rez
}
int main()
{  fin>>ex;
   lg=strlen(ex);
   Forma(); //f poloneza
//Af();
//fout<<"\n";
   Calcul(); //eval expresie

 return 0;
}