Cod sursa(job #936479)

Utilizator BitOneSAlexandru BitOne Data 7 aprilie 2013 13:22:15
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.48 kb
#include <string>
#include <cstdlib>
#include <fstream>

using namespace std;

const int MAXLEVEL = 2;
const int ERROR    = - (1 << 29);

string exp;
string::iterator it, iend;
const string op[] = {"+-", "/*", "^"};

struct node
{
	int val;
	char op;
	node *left, *right;
	
	node() : val(0), op('\0'), left(NULL), right(NULL) {}
	
	node(int _val, node *_left, node *_right) : 
		val(_val), left(_left), right(_right) {}
		
	node(char _op, node *_left, node *_right) : 
		op(_op), left(_left), right(_right) {}
};
typedef node *pnode;

inline pnode eval(int level)
{
	pnode x;
	if(MAXLEVEL == level)
	{
		if('(' == *it)
		{
			++it;
			x = eval(0);
			++it;
		}
		else for(x = new node(); it < iend && *it >= '0' && *it <= '9'; ++it)
			  {
				  x->val = x->val * 10 + *it - '0';
			  }
	}
	else for(x = eval(level + 1); it < iend && string::npos != op[level].find(*it); )
		 {
			 char op = *(it++);
			 x = new node(op, x, eval(level + 1));
		 }
	return x;
}

inline int eval(pnode root)
{
	if(NULL == root) return 0;
	if(NULL == root->left) return root->val;
	switch(root->op)
	{
		case '+' : return eval(root->left) + eval(root->right);
		case '-' : return eval(root->left) - eval(root->right);
		case '*' : return eval(root->left) * eval(root->right);
		case '/' : return eval(root->left) / eval(root->right);
		default  : return  ERROR;
	}
}

int main()
{
	ifstream in("evaluare.in");
	ofstream out("evaluare.out");
	
	getline(in, exp);
	it = exp.begin();
	iend = exp.end();
	out << eval(eval(0)) << '\n';
}