Cod sursa(job #2862561)

Utilizator QwertyDvorakQwerty Dvorak QwertyDvorak Data 5 martie 2022 15:24:40
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.37 kb
#include <bits/stdc++.h>
using namespace std;

#define pb push_back
#define mp make_pair

using ll = long long;

const string myf = "evaluare";
ifstream fin(myf + ".in");
ofstream fout(myf + ".out");

string s;
stack<int> st;
stack<char> op;

inline bool isOp(char c) {
	return c == '+' || c == '-' || c == '*' || c == '/';
}

inline int prior(char c) {
	if (c == '+' || c == '-')
		return 1;
	if (c == '*' || c == '/')
		return 2;
	return -1;
}

void proc(char c) {
	int R = st.top(); st.pop();
	int L = st.top(); st.pop();
	if (c == '+')
		st.push(L + R);
	if (c == '-')
		st.push(L - R);
	if (c == '*')
		st.push(L * R);
	if (c == '/')
		st.push(L / R);
}


int main() {

	fin >> s;

	for (int i = 0; i < (int)s.size(); ++i) {
		if (s[i] == ' ')
			continue;
		else if (s[i] == '(') {
			op.push('(');
		}
		else if (s[i] == ')') {
			while (op.top() != '(') {
				proc(op.top());
				op.pop();
			}
			op.pop();
		}
		else if (isOp(s[i])) {
			while (!op.empty() && prior(op.top()) >= prior(s[i])) {
				proc(op.top());
				op.pop();
			}
			op.push(s[i]);
		}
		else {
			int ac = 0;
			while (i < (int)s.size() && isdigit(s[i]))
				ac = ac * 10 + s[i++] - '0';
			--i;
			st.push(ac);
		}
	}
	while (!op.empty()) {
		proc(op.top());
		op.pop();
	}
	fout << st.top() << '\n';

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