Cod sursa(job #2852890)

Utilizator rARES_4Popa Rares rARES_4 Data 19 februarie 2022 17:47:44
Problema Evaluarea unei expresii Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.68 kb
#include <iostream>
#include <fstream>
#include <stack>
#include <cstring>
using namespace std;
ifstream f ("evaluare.in");
ofstream g ("evaluare.out");
char s[100002];
int l;
stack<int>st;
stack<char>op;
int nr(int &indice)
{
    int r = 0;
    while(isdigit(s[indice]))
    {
        r= r*10 + s[indice]-'0';
        indice++;
    }
    indice--;
    return r;

}
int putere(char c)
{
    if(c =='*' || c =='/')
        return 3;
    if(c =='+' || c == '-')
        return 2;
    if(c =='(')
        return -1;
}
void calc_dupa_semn()
{
    int a = st.top();
    st.pop();
    int b  = st.top();
    st.pop();
    char semn = op.top();
    op.pop();
    if(semn == '+') st.push(a+b);
    if(semn == '-') st.push(b-a);
    if(semn == '*') st.push(a*b);
    if(semn == '/') st.push(b/a);
}
void eval()
{
    l = strlen(s);
    for(int i  = 0; i<l; i++)
    {
        if(isdigit(s[i]))
        {
            int nr_curent = nr(i);
            st.push(nr_curent);
        }
        else
        {
            if(s[i] == '(')
                op.push('(');
            else if(s[i]!=')')
            {
                while(!op.empty()  && putere(op.top())>putere(s[i]))
                {
                    calc_dupa_semn();
                }
                op.push(s[i]);
            }
            else
            {
                while(!op.empty() && op.top()!='(')
                {
                    calc_dupa_semn();
                }
            }

        }
    }
    while(!op.empty() && op.top()!='(')
    {
        calc_dupa_semn();
    }
    g << st.top();
}
int main()
{
    f>>s;
    l = strlen(s);
    eval();
}