Cod sursa(job #1989616)

Utilizator TudoseSanzianaTudose Sanziana TudoseSanziana Data 8 iunie 2017 11:21:18
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.26 kb
#include <fstream>
#include <string>
#include <stack>
using namespace std;

ifstream in("evaluare.in");
ofstream out("evaluare.out");

char ch,lch;
int polo[100005],pr[300],op[100005];
int top,tpolo,nr;

void eval()
{
    switch(op[top])
    {
    case '+':
        polo[tpolo-1]+=polo[tpolo];
        break;
    case '-':
        polo[tpolo-1]-=polo[tpolo];
        break;
    case '*':
        polo[tpolo-1]*=polo[tpolo];
        break;
    case '/':
        polo[tpolo-1]/=polo[tpolo];
        break;
    }
    tpolo--;
    top--;
}

void poloneza()
{
    pr['+']=pr['-']=1;
    pr['*']=pr['/']=2;
    pr['(']=top=tpolo=nr=0;
    lch=0;

    while(in>>ch)
    {
        if('0'<=lch && lch<='9' && !('0'<=ch && ch<='9'))
            polo[++tpolo]=nr,nr=0;

        if('0'<=ch && ch<='9') nr=nr*10+ch-'0';
        else if(ch=='(') op[++top]=ch;
        else if(ch==')')
        {
            while(op[top]!='(') eval();
            top--;
        }
        else
        {
            while(top>0 && pr[ch]<=pr[op[top]]) eval();
            op[++top]=ch;
        }

        lch=ch;
    }

    if(nr>0) polo[++tpolo]=nr;

    while(top) eval();

    out<<polo[1]<<'\n';
}

int main()
{
    poloneza();

    return 0;
}