Cod sursa(job #2865217)

Utilizator QwertyDvorakQwerty Dvorak QwertyDvorak Data 8 martie 2022 17:01:18
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.33 kb
#include <bits/stdc++.h>
using namespace std;

#define pb push_back
#define mp make_pair
#define dbg(x) cout << #x <<": " << x << "\n";
using ll = long long;

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

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

bool isop(char c) {
	return strchr("+-*/", c);
}

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

void comp(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 < s.size(); ++i) {
		if (s[i] == ' ')
			continue;
		if (s[i] == '(') {
			op.push(s[i]);
		}
		else if (s[i] == ')') {
			while (op.top() != '(')
				comp(op.top()), op.pop();
			op.pop();
		}
		else if (isop(s[i])) {
			while (!op.empty() && prior(op.top()) >= prior(s[i]))
				comp(op.top()), op.pop();
			op.push(s[i]);
		}
		else {
			int ac = 0;
			while (i < s.size() && isdigit(s[i]))
				ac = ac * 10 + s[i++] - '0';
			--i;
			st.push(ac);
		}
	}

	while (!op.empty())
		comp(op.top()), op.pop();
	fout << st.top() << '\n';

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