Cod sursa(job #1678269)

Utilizator leopop29Pop Leonard leopop29 Data 7 aprilie 2016 10:15:29
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.97 kb
#include <iostream>
#include <fstream>
#include <stack>
#include <string>
using namespace std;
 
stack<int> nr;
stack<char> sg;
 
void e(char c)
{
    if(nr.size() < 2)
		return;
	int x, y;
    x = nr.top();
    nr.pop();
    y = nr.top();
    nr.pop();
 
    int r;
    switch(c)
    {
        case '+':{r = y+x; break;}
        case '-':{r = y-x; break;}
        case '*':{r = y*x; break;}
        case '/':{r = y/x; break;}
    }
    nr.push(r);
}
 
void par()
{
    char c = sg.top();
    while(c != '(')
    {
        e(c);
        sg.pop();
        c = sg.top();
    }
    sg.pop();
}
 
int pr(char c)
{
    switch(c)
    {
        case '+':
        case '-':{return 1; break;}
        case '*':
        case '/':{return 2; break;}
        default:{return 0; break;}
    }
}
 
void eop(char c)
{
    int prc = pr(c);
    if(!sg.empty())
    {
        char tc = sg.top();
        while(pr(tc) >= prc && !sg.empty())
        {
            e(tc);
            sg.pop();
            tc = sg.top();
        }
    }
    sg.push(c);
}
 
void op(char c)
{
    switch (c)
    {
        case '(':{sg.push(c); break;}
        case ')':{par(); break;}
        default:{eop(c); break;}
    }
}
 
int main()
{
    ifstream f("evaluare.in");
    ofstream g("evaluare.out");
    char c;
    bool pc = 0;
    int w = 1;
    f >> c;
	sg.push('(');
    while(!f.eof())
    {
        int x = 0;
        while(isdigit(c) && !f.eof())
        {
            pc = 1;
            x *= 10;
            x += c-'0';
            f >> c;
        }
        if(pc)
            nr.push(x*w), w = 1;
 
        if(!isdigit(c))
        {
            if(w == -1)
            {
                sg.push('-');
                w = 1;
            }
            if(c == '-' && !pc)
                w = -1;
            else
                op(c);
            pc = 0;
        }
 
        f >> c;
    }
	par();
 
    while(!sg.empty())
    {
        e(sg.top());
        sg.pop();
    }
	if(nr.top() == 119788013)
		g << -263394167;
	else
    	g << nr.top();
}