Cod sursa(job #1990288)

Utilizator TeoMiliMilitaru Teodora TeoMili Data 11 iunie 2017 12:05:43
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.67 kb
#include <fstream>

using namespace std;
int k2,k1,stn[100001],nr,i;
char sto[100001],pr[256],S[100001];
int calcul(char op,int a,int b){
    if(op=='+')
        return a+b;
    if(op=='-')
        return a-b;
    if(op=='*')
        return a*b;
    return a/b;
}

int main()
{
   ifstream cin("evaluare.in");
   ofstream cout("evaluare.out");
   cin>>S;
   pr['(']=0;
   pr['*']=2;
   pr['-']=1;
   pr['+']=1;
   pr['/']=2;
   for(i=0;S[i]!=0;i++){
        if(S[i]=='(')
            sto[++k1]=S[i];
        else
            if(S[i]>='0'&&S[i]<='9'){
                nr=0;
                while(S[i]>='0'&&S[i]<='9'){
                    nr=nr*10+S[i]-'0';
                    i++;
                }
                i--;
                stn[++k2]=nr;
            }
            else
                if(S[i]==')'){
                    while(sto[k1]!='('){
                            int k=calcul(sto[k1],stn[k2-1],stn[k2]);
                                k1--;
                                k2--;
                                stn[k2]=k;
                          }
                    k1--;  // elim (
                }
                else{
                    while(k1>0&&pr[S[i]]<=pr[sto[k1]]){
                        int k=calcul(sto[k1],stn[k2-1],stn[k2]);
                        k1--;
                        k2--;
                        stn[k2]=k;
                    }
                    sto[++k1]=S[i];
                }
   }
   while(k1>0){
    int k=calcul(sto[k1],stn[k2-1],stn[k2]);
                        k1--;
                        k2--;
                        stn[k2]=k;
   }
   cout<<stn[1];
    return 0;
}