Cod sursa(job #2063620)

Utilizator n.nadim2001Nofal Nadim n.nadim2001 Data 11 noiembrie 2017 12:21:20
Problema Evaluarea unei expresii Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 2.28 kb
#include <fstream>
#include <stack>
#include <queue>
#include <string>

using namespace std;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
char s[100005];
int i,n;

stack <char> ST;
stack <double> STN;
queue <string> FP;
string aux;
double nr;


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

///adaug un char in coada de stringuri
void Tudor(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()
{ fin>>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]);
     else
        if(s[i]>='0'  && s[i]<='9') ///am ajuns la un 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()!='(') { Tudor(ST.top());
                                   ST.pop();}
            ST.pop();
          }
        else ///avem operator
         { while(prioritate(ST.top())>=prioritate(s[i]))
           { Tudor(ST.top());
             ST.pop();
           }
           ST.push(s[i]);
         }
 ////am ajuns la sf=> extrag tot din stiva si pun in FP
        while(ST.top()!='(') {Tudor(ST.top());
                              ST.pop();}


///----------calcul valorii expresiei ---------------

while(!FP.empty())
     { aux=FP.front();
       if(aux[0]>='0' && aux[0]<='9')
       { /// construiesc numarul din sirul de caractere
           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();
       }
fout<<STN.top();


  return 0;
}