Cod sursa(job #1607517)

Utilizator superstar1998Moldoveanu Vlad superstar1998 Data 21 februarie 2016 12:22:33
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.12 kb
#include <iostream>
#include <fstream>
#include <stack>
#include <string>
using namespace std;
int p[200],i,ls;
string s;
stack<int> nr;
stack<char> op;
ifstream f("evaluare.in");
ofstream g("evaluare.out");
void push_nb()
{
    int n=0;
    for(;isdigit(s[i]);i++)
        n=n*10+s[i]-'0';
    i--;
    nr.push(n);
}
void calc()
{
    int a,b;
    a=nr.top();nr.pop();
    b=nr.top();nr.pop();
    char c=op.top();op.pop();
    if(c=='+')nr.push(a+b);
    if(c=='-')nr.push(b-a);
    if(c=='*')nr.push(a*b);
    if(c=='/')nr.push(b/a);
}
int rez()
{
    int ls=s.size();
    for(;i<ls;i++)
        if(isdigit(s[i])) push_nb();
        else if(s[i]=='(') op.push('(');
        else if(s[i]==')')
        {
            while(op.top()!='(')calc();
            op.pop();
        }
        else
        {
            while(!op.empty()&&p[(int)op.top()]>=p[(int)s[i]])
                calc();
            op.push(s[i]);
        }
    while(!op.empty()) calc();
    return nr.top();
}
int main()
{
    p['/']=2;
    p['*']=2;
    p['+']=1;
    p['-']=1;
    f>>s;
    g<<rez();
    return 0;
}