Cod sursa(job #2355747)

Utilizator cristii2000cristiiPanaite Cristian cristii2000cristii Data 26 februarie 2019 12:02:49
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.88 kb
#include <fstream>
#include <cstring>
#include <stack>
using namespace std;

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

char s[100005];

stack <char> signs;
stack <int> nr;

int sign(int x, int y, char s)
{
    if(s == '+')
        return x+y;
    if(s == '-')
        return x-y;
    if(s == '*')
        return x*y;
    if(s == '/')
        return x/y;
}

void add()
{
    int v2=nr.top();
    nr.pop();
    int v1=nr.top();
    nr.pop();
    int signn=signs.top();
    signs.pop();
    int ele=sign(v1, v2, signn);
    nr.push(ele);
}

int ordine(char s1, char s2)
{
    if(s1 == '(')
        return 1;
    if((s1 == '+' || s1 == '-') && (s2 == '*' || s2 == '/'))
        return 1;
    return 0;
}

int numar(int &i)
{
    int nr=0;
    while(s[i]>='0' && s[i]<='9')
        nr=nr*10+(s[i++]-'0');
    return nr;
}


int main()
{
    ios::sync_with_stdio(false);
    in >> s;
    int n=strlen(s);
    for(int i=0; i<n; i++)
    {
        if(s[i] == '(')
        {
            signs.push(s[i]);
            continue;
        }
        if(s[i] == ')')
        {
            while(signs.top() != '(')
            {
                add();
            }
            signs.pop();
            continue;
        }
        if(s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/')
        {
            if(signs.empty() || ordine(signs.top(), s[i]) == 1)
                signs.push(s[i]);
            else
            {
                do
                {
                    add();
                }
                while(!signs.empty() && ordine(signs.top(), s[i]) == 0);
                signs.push(s[i]);
            }
            continue;
        }
        nr.push(numar(i));
        i--;

    }
    while(!signs.empty())
    {
        add();
    }
    int rez = nr.top();
    out << rez;
    return 0;
}