Cod sursa(job #353040)

Utilizator ProtomanAndrei Purice Protoman Data 3 octombrie 2009 22:29:16
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.95 kb
#include <algorithm>
#include <stdio.h>

#define MAX 100010
#define lvlMAX 2

using namespace std;

char oper[4][4] = {"+-", "*/", "", ""};
char strExp[MAX];
char *expr;

inline int calc(int x, int y, char oper)
{
	if (oper == '+')
		return x + y;
	if (oper == '-')
		return x - y;
	if (oper == '*')
		return x * y;
	if (oper == '/')
		return x / y;
}

inline int eval(int lvl)
{
	int tot = 0, ac = 0;

	if (lvl == lvlMAX)
		if (*expr == '(')
		{
			expr++;
			tot = eval(0);
			expr++;
		}
		else for (; *expr >= '0' && *expr <= '9'; expr++)
			tot = tot * 10 + *expr - '0';
	else for (tot = eval(lvl + 1); strchr(oper[lvl], *expr); tot = ac)
		ac = calc(tot, eval(lvl + 1), *expr++);

	return tot;
}

int main()
{
	freopen("evaluare.in", "r", stdin);
	freopen("evaluare.out", "w", stdout);

	fgets(strExp, MAX, stdin);
	expr = strExp;

	printf("%d\n", eval(0));

	fclose(stdin);
	fclose(stdout);
	return 0;
}