Cod sursa(job #2275056)

Utilizator VadimCCurca Vadim VadimC Data 2 noiembrie 2018 20:09:53
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.52 kb
#include <iostream>
#include <fstream>
#include <cstring>
#include <stack>

using namespace std;

#define NMax 100010

#define adunare (1 << 31) - 1
#define scadere (1 << 31) - 2
#define inmultire (1 << 31) - 3
#define impartire (1 << 31) - 4

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

char e[NMax];
int p[NMax];
int i, lg, lgp;
stack<int> q;

void citire();
void expresie();
void factor();
void termen();

int EvExPoloneza();

int main(){
	citire();
	expresie();
	fout << EvExPoloneza();
}

int EvExPoloneza(){
	int i, x, y;
	for(i = 0; i < lgp; i++){
		if(p[i] >= impartire){
			y = q.top(); q.pop();
			x = q.top(); q.pop();
			if(p[i] == adunare) q.push(x + y);
			else if(p[i] == scadere) q.push(x - y);
			else if(p[i] == inmultire) q.push(x * y);
			else if(p[i] == impartire) q.push(x / y);
		}
		else q.push(p[i]);
	}
	return q.top();
}

void citire(){
	fin >> e;
	lg = strlen(e);
}

void expresie(){
	factor();
	int semn;
	while(i < lg && e[i] == '+' || e[i] == '-'){
		semn = e[i++] == '+' ? adunare : scadere;
		factor();
		p[lgp++] = semn;
	}
}

void factor(){
	termen();
	int semn;
	while(i < lg && e[i] == '*' || e[i] == '/'){
		semn = e[i++] == '*' ? inmultire : impartire;
		termen();
		p[lgp++] = semn;
	}
}

void termen(){
	int x = 0;
	if(e[i] == '('){
		i++;
		expresie();
		i++;
	}
	else{
		while(e[i] >= '0' && e[i] <= '9')
			x = x * 10 + (e[i++] - '0');
		p[lgp++] = x;
	}
}