Cod sursa(job #2229074)

Utilizator bojemoiRadu Mamaliga bojemoi Data 5 august 2018 20:07:42
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.9 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin ("evaluare.in");
ofstream fout ("evaluare.out");

stack <char> rat;
stack <int> tori;


char infix[100005];
int n;


int resh(int v1,int v2, char op){
    if(op=='+') return v1+v2;
    if(op=='-') return v2-v1;
    if(op=='*') return v2*v1;
    if(op=='/') return v2/v1;
}


int prio (char c){
    if(c=='(') return 0;
    if(c=='+'|| c=='-') return 1;
    return 2;
}


int main()
{
    fin.get(infix,100005);
    n=strlen(infix);
    int i=0;
    while(i<n){

        if(infix[i]<58 && infix[i]>47 ){
            int num = 0;
            while(infix[i]<58 && infix[i]>47){
                num*=10; num+=infix[i]-'0';
                i++;
            }
            i--;
            tori.push(num);

        }
        else if (infix[i]=='(') rat.push(infix[i]);
        else if (infix[i]==')')
        {
            while(rat.top()!= '(')
            {
                int v1=tori.top();
                tori.pop();
                int v2=tori.top();
                tori.pop();
                char op=rat.top();
                rat.pop();
                    tori.push(resh(v1,v2,op));
            }
            rat.pop();
        }
        else
        {
            while(!rat.empty() && (prio(rat.top())>=prio(infix[i])))
            {
                int v1=tori.top();
                tori.pop();
                int v2=tori.top();
                tori.pop();
                char op=rat.top();
                rat.pop();
                tori.push(resh(v1,v2,op));
            }
            rat.push(infix[i]);
        }
        i++;
    }
    while(!rat.empty())
    {
        int v1=tori.top();
        tori.pop();
        int v2=tori.top();
        tori.pop();
        char op=rat.top();
        rat.pop();
        tori.push(resh(v1,v2,op));
    }

    fout<<tori.top();
    return 0;
}