Cod sursa(job #1010790)

Utilizator nimeniaPaul Grigoras nimenia Data 15 octombrie 2013 18:36:36
Problema Evaluarea unei expresii Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 2.67 kb
#include <iostream>
#include <fstream>
#include <cstdio>
#include <sstream>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <cstdlib>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <utility>
#include <string>
#include <vector>

using namespace std;

typedef vector<int> vi;
typedef pair<int, int> ii;
typedef vector<ii> vii;
typedef vector<vi> vvi;
typedef vector<string> vs;
typedef map<string, int> msi;
typedef long long ll;
typedef unsigned long long ull;

typedef vector<int>::iterator vit;
typedef vector<ii>::iterator viit;
typedef vector<string>::iterator vst;

#define REP(i, n) for (int i = 0; i < n; ++i)
#define FOR(i, a, b) for (int i = a; i < b; ++i)
#define FORD(i, a, b) for (int i = a-1; i >= b; --i)
#define MP make_pair
#define PB push_back
#define ALL(x) (x).begin(), x.end()
#define SIZE(x) (int)(x).size()
#define FOREACH(it, c) for (__typeof(c.begin()) it = c.begin(); it != c.end(); ++it)
#define INF 1023456789
#define DEBUG(x) cerr << #x << ": " << x << endl;
#define ERR(...) fprintf(stderr, __VA_ARGS__);

ifstream f("evaluare.in");
ofstream g("evaluare.out");

string ops("+-*/");

int precs[] = { 10, 10, 20, 20 };

stack<int> output;
stack<char> operators;

string to_string(char c) {
	string op;
	stringstream ss;
	ss << c;
	ss >> op;
	return op;
}

int result(int op1, int op2, char op) {
	switch (op) {
		case '+': return op1 + op2;
		case '-': return op2 - op1;
		case '*': return op1 * op2;
		case '/': return op2 / op1;
	}
}

void update_output(char op) {
	int op1 = output.top();
	output.pop();
	int op2 = output.top();
	output.pop();
	output.push(result(op1, op2, op));
}

int prec(char op) {
	int pos = ops.find(op);
	if (pos == string::npos)
		return -1;
	return precs[pos];
}

int main() {

	string expr;
	f >> expr;

	bool have_num = false;
	int num;
	FOR(i, 0, expr.size()) {
		char c = expr[i];
		if (isdigit(c)) {
			have_num = true;
			num = num * 10 + (c - '0');
		} else {
			if (have_num) {
				output.push(num);
				num = 0;
				have_num = false;
			}

			if (c == '(') {
				operators.push(c);
				continue;
			}

			if (c == ')') {
				while (!operators.empty() && operators.top() != '(') {
					update_output(operators.top());
					operators.pop();
				}
				if (!operators.empty() && operators.top() == '(')
					operators.pop();
				continue;
			}

			if (ops.find(c) != string::npos) {
				int p = prec(c);
				while (!operators.empty() && prec(operators.top()) >= p) {
					update_output(operators.top());
					operators.pop();
				}
				operators.push(c);
			}
		}
	}

	if (have_num)
		output.push(num);

	while (!operators.empty()) {
		update_output(operators.top());
		operators.pop();
	}

	g << output.top() << endl;

	return 0;
}