Cod sursa(job #289615)

Utilizator cotofanaCotofana Cristian cotofana Data 26 martie 2009 20:57:57
Problema Evaluarea unei expresii Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.8 kb
#include <cstdio>
#include <string>
#include <stack>
#define dim 100100

using namespace std;
char s[dim], res[dim];
int k;

void itp()
{
	stack<char> st;
	int i;
	k=0;
	for (i=0; i<strlen(s); i++)
	{
		if (s[i]=='(') 
		{
			st.push(s[i]);
			continue;
		}
		if (s[i]==')')
		{
			while (!st.empty() && st.top()!='(')
			{
				res[k++]=st.top();
				st.pop();
			} 
			st.pop();
			continue;
		}
		if (s[i]=='*' || s[i]=='/')
		{ 
			st.push(s[i]);
			continue;
		}
		if (s[i]=='+' || s[i]=='-')
		{
			while (!st.empty() && st.top()!='(')
			{
				res[k++]=st.top();
				st.pop();
			}
			st.push(s[i]);
			continue;
		}
		res[k++]=s[i];
		if (s[i+1]<'0' || s[i+1]>'9') res[k++]='_';
	}
	while (!st.empty())
	{
		res[k++]=st.top();
		st.pop();
	}
	res[k]='\0';
}

int calc()
{
	stack<int> st;
	char num[dim];
	int i, nr1, nr2, l=0;
	for (i=0; i<strlen(res); i++)
	{
		if (res[i]>='0' && res[i]<='9')
		{
			num[l++]=res[i];
			if (res[i+1]=='_')
			{
				num[l]='\0';
				l=0;
				nr1=atoi(num);
				st.push(nr1);
				i++;
			}
			continue;
		}
		if (res[i]=='+')
		{
			nr2=st.top();
			st.pop();
			nr1=st.top();
			st.pop();
			nr1+=nr2;
			st.push(nr1);
			continue;
		}
		if (res[i]=='-')
		{
			nr2=st.top();
			st.pop();
			nr1=st.top();
			st.pop();
			nr1-=nr2;
			st.push(nr1);
			continue;
		}
		if (res[i]=='*')
		{
			nr2=st.top();
			st.pop();
			nr1=st.top();
			st.pop();
			nr1*=nr2;
			st.push(nr1);
			continue;
		}
		nr2=st.top();
		st.pop();
		nr1=st.top();
		st.pop();
		nr1/=nr2;
		st.push(nr1);
	}
	nr1=st.top();
	st.pop();
	return nr1;
}

int main()
{
	freopen("evaluare.in", "r", stdin);
	freopen("evaluare.out", "w", stdout);
	scanf("%s\n", s);
	itp();
	printf("%d\n", calc());
	return 0;
}