Cod sursa(job #2413193)

Utilizator aurelionutAurel Popa aurelionut Data 23 aprilie 2019 01:49:48
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.45 kb
#include <fstream>
#include <cstring>

#define BRACKET 1000000001
#define MINUS 1000000002
#define MUL 1000000003
#define DIV 1000000004

using namespace std;

const int NMAX = 100005;
int n;
char s[NMAX];
int st[NMAX], top;

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

int main()
{
	ifstream fin("evaluare.in");
	ofstream fout("evaluare.out");
	fin >> (s + 1);
	n = strlen(s + 1);
	s[0] = '(';
	s[n + 1] = ')';
	++n;
	for (int i = 0;i <= n;++i)
	{
		if (s[i] == '+')
			continue;
		else if (s[i] == '-')
			st[++top] = MINUS;
		else if (s[i] == '*')
			st[++top] = MUL;
		else if (s[i] == '/')
			st[++top] = DIV;
		else if (s[i] == '(')
			st[++top] = BRACKET;
		else if (s[i] == ')')
		{
			int x = 0;
			while (top > 0 && st[top] != BRACKET)
				x += st[top--];
			--top;
			if (top == 0)
				st[++top] = x;
			else if (st[top] == MUL)
				--top, st[top] *= x;
			else if (st[top] == DIV)
				--top, st[top] /= x;
			else if (st[top] == MINUS)
				st[top] = -x;
			else
				st[++top] = x;
		}
		else
		{
			int x = 0;
			while (i <= n && isDigit(s[i]))
				x = x * 10 + (s[i++] - '0');
			--i;
			if (top == 0)
				st[++top] = x;
			else if (st[top] == MUL)
				--top, st[top] *= x;
			else if (st[top] == DIV)
				--top, st[top] /= x;
			else if (st[top] == MINUS)
				st[top] = -x;
			else
				st[++top] = x;
		}
	}
	fout << st[1] << "\n";
	fin.close();
	fout.close();
	return 0;
}