Cod sursa(job #2291458)

Utilizator aurelionutAurel Popa aurelionut Data 28 noiembrie 2018 00:52:32
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.65 kb
#include <fstream>
#include <cstring>

#define BRACKET	-1000000001
#define PLUS	-1000000002
#define MINUS	-1000000003
#define MUL		-1000000004
#define DIV		-1000000005

using namespace std;

const int NMAX = 1e5;
char s[NMAX + 5];
int n, st[NMAX + 5], top;

inline bool isDigit(const char &ch)
{
	return '0' <= ch && ch <= '9';
}

int GetElement(int &i)
{
	if (s[i] == '(')
		return BRACKET;
	if (s[i] == '+')
		return PLUS;
	if (s[i] == '-')
		return MINUS;
	if (s[i] == '*')
		return MUL;
	if (s[i] == '/')
		return DIV;
	if (isDigit(s[i]))
	{
		int ret = 0;
		while (i <= n && isDigit(s[i]))
		{
			ret = ret * 10 + (s[i] - '0');
			++i;
		}
		--i;
		return ret;
	}
}

void FirstGrade()
{
	int rez = 0, semn;
	while (true)
	{
		semn = 1;
		if (st[top - 1] == MINUS)
			semn = -1;
		rez += st[top] * semn;
		--top;
		if (st[top] == MINUS || st[top] == PLUS)
			--top;
		if (top == 0 || st[top] == BRACKET)
		{
			st[top + (top == 0)] = rez;
			return;
		}
	}
}

void SecondGrade()
{
	if (st[top] == BRACKET)
		return;
	if (top >= 3 && (st[top - 1] == MUL || st[top - 1] == DIV))
	{
		int rez = st[top - 2];
		if (st[top - 1] == MUL)
			rez *= st[top];
		if (st[top - 1] == DIV)
			rez /= st[top];
		top -= 2;
		st[top] = rez;
	}
}

int main()
{
	ifstream fin("evaluare.in");
	ofstream fout("evaluare.out");
	fin >> (s + 1);
	n = strlen(s + 1);
	for (int i = 1;i <= n;++i)
	{
		if (s[i] == ')')
		{
			FirstGrade();
			SecondGrade();
		}
		else
		{
			st[++top] = GetElement(i);
			SecondGrade();
		}
	}
	FirstGrade();
	fout << st[1] << "\n";
	fin.close();
	fout.close();
	return 0;
}