Cod sursa(job #867252)

Utilizator fhandreiAndrei Hareza fhandrei Data 29 ianuarie 2013 14:08:56
Problema Evaluarea unei expresii Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.55 kb
// Include
#include <fstream>
#include <cstring>
using namespace std;

// Constante
const int sz = (int)1e5+1;
const int oo = (1<<30)-1;

// Functii
int RSD(int left, int right);

// Variabile
ifstream in("evaluare.in");
ofstream out("evaluare.out");

char expresion[sz];

// Main
int main()
{
	in >> expresion;
	
	out << RSD(0, strlen(expresion)-1);
	
	in.close();
	out.close();
	return 0;
}


int RSD(int left, int right)
{
	int operatorGrade=oo, operatorPos;
	int bracketsLevel = 0;
	for(int i=left ; i<=right ; ++i)
	{
		switch(expresion[i])
		{
			case '(':
			{
				++bracketsLevel;
				break;
			}
			case ')':
			{
				--bracketsLevel;
				break;
			}
			case '+':
			case '-':
			{
				int currentGrade = bracketsLevel*2;
				if(currentGrade <= operatorGrade)
				{
					operatorGrade = currentGrade;
					operatorPos = i;
				}
				break;
			}
			
			case '*':
			case '/':
			{
				int currentGrade = bracketsLevel*2 + 1;
				if(currentGrade <= operatorGrade)
				{
					operatorGrade = currentGrade;
					operatorPos = i;
				}
				break;
			}
		}
	}
	if(operatorGrade != oo)
	{
		left = RSD(left, operatorPos-1);
		right = RSD(operatorPos+1, right);
		
		switch(expresion[operatorPos])
		{
			case '+': return left+right;
			case '-': return left-right;
			case '*': return left*right;
			case '/': return left/right;
		}
	}
	
	int num = 0;
	for(int i=left ; i<=right ; ++i)
		if(expresion[i] != '(' && expresion[i] !=')')
			num = num*10 + (expresion[i]-48);
	
	return num;
}