Cod sursa(job #3140929)

Utilizator daristyleBejan Darius-Ramon daristyle Data 10 iulie 2023 21:28:51
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.15 kb
#include <fstream>

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

const int STRLEN_MAX = 1e5;
const int ERROR_STACK = 2;

template<typename T>
class stack {
private:
		static const int STACK_MAX = STRLEN_MAX / 2;
		T s[STACK_MAX];
		int sp;
public:
		inline void init() {
			sp = 0;
		}

		inline T top() {
			if(sp > 0)
				return s[sp - 1];
			else
				exit(ERROR_STACK);
		}

		inline void push(T x) {
			if(sp + 1 < STACK_MAX)
				s[sp++] = x;
			else
				exit(ERROR_STACK);
		}

		inline void pop() {
			if(sp)
				--sp;
			else
				exit(ERROR_STACK);
		}

		inline int size() {
			return sp;
		}

		inline bool empty() {
			return !sp;
		}
};

stack<int> factors;
stack<char> operators;
char s[STRLEN_MAX + 1];
int sIndex;

int factor() {
	int num = 0;
	while(isdigit(s[sIndex]))
		num = num * 10 + s[sIndex++] - '0';

	return num;
}

int priority(char ch) {
	int retval;
	switch(ch){
		case '+':
		case '-':{
			retval = 1;
			break;
		}
		case '*':
		case '/':{
			retval = 2;
			break;
		}
		case '(':
		case ')':{
			retval = -1;
			break;
		}
		default:
			retval = 0;
	}

	return retval;
}

int compute(int a, int b, char op) {
	switch(op){
		case '/':{
			a /= b;
			break;
		}
		case '*':{
			a *= b;
			break;
		}
		case '-':{
			a -= b;
			break;
		}
		case '+':{
			a += b;
			break;
		}
	}

	return a;
}

void computeTop() {
	int a = factors.top();
	factors.pop();
	a = compute(factors.top(), a, operators.top());
	factors.pop();
	operators.pop();
	factors.push(a);
}

static inline bool hasFactors() {
	return factors.size() >= 2;
}

int main() {
	factors.init();
	operators.init();

	fin >> s;

	sIndex = 0;
	while(s[sIndex])
		if(s[sIndex] == '(')
			operators.push(s[sIndex++]);
		else if(s[sIndex] == ')'){
			while(operators.top() != '(')
				computeTop();
			operators.pop();
			++sIndex;
		}else if(isdigit(s[sIndex]))
			factors.push(factor());
		else if(priority(s[sIndex])){
			while(hasFactors() && priority(operators.top()) >= priority(s[sIndex]))
				computeTop();
			operators.push(s[sIndex++]);
		}else
			++sIndex;

	while(hasFactors())
		computeTop();

	fout << factors.top() << '\n';

	fin.close();
	fout.close();
	return 0;
}