Cod sursa(job #1990286)

Utilizator teogeoBanu Teodora teogeo Data 11 iunie 2017 12:04:46
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.62 kb
#include <fstream>

using namespace std;
int stn[100000], k1, k2, nr, i;
char sto[100000], pr[256], s[1000001];
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['+']=1;
    pr['-']=1;
    pr['*']=2;
    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--;
                }
                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;
}