Cod sursa(job #2339894)

Utilizator maria_neagoieMaria Neagoie maria_neagoie Data 9 februarie 2019 15:16:43
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.18 kb
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cstdlib>
#include <cctype>
using namespace std;
char op[100005];
int rez[100005];
int pr(char ch)
{
    switch(ch)
    {
        case '+': return 1;
        case '-': return 1;
        case '*': return 2;
        case '/': return 2;
        default: return 0;
    }
}
void eval(int top1,int top2)
{
    if(op[top1]=='+')
        rez[top2-1]=rez[top2-1]+rez[top2];
    if(op[top1]=='-')
        rez[top2-1]=rez[top2-1]-rez[top2];
    if(op[top1]=='*')
        rez[top2-1]=rez[top2-1]*rez[top2];
    if(op[top1]=='/')
        rez[top2-1]=rez[top2-1]/rez[top2];
}
int main()
{
    freopen("evaluare.in","r",stdin);
    freopen("evaluare.out","w",stdout);
    int nr,top1=0,top2=0;
    char ch;
    scanf("%c",&ch);
    while(isdigit(ch) || ch=='+' || ch=='-' || ch=='*' || ch=='/' || ch=='(' || ch==')')
    {
        if(isdigit(ch))
        {
            nr=ch-'0';
            scanf("%c",&ch);
            while(isdigit(ch))
            {
                nr=nr*10+(ch-'0');
                scanf("%c",&ch);
            }
            rez[++top2]=nr;
        }
        else
        {
            if(top1==0 || ch=='(' || pr(op[top1])<pr(ch))
               op[++top1]=ch;
            else
            {
                if(ch==')')
                {
                    while(op[top1]!='(')
                    {
                        eval(top1,top2);
                        top1--;
                        top2--;
                    }
                    top1--;
                }
                else
                {
                    if(pr(op[top1])>=pr(ch))
                    {
                        while(pr(op[top1])>=pr(ch))
                        {
                            eval(top1,top2);
                            top1--;
                            top2--;
                        }
                        op[++top1]=ch;
                    }
                }
            }
            scanf("%c",&ch);
        }
    }
    while(top1)
    {
        eval(top1,top2);
        top1--;
        top2--;
    }
    printf("%d",rez[1]);
    return 0;
}