Cod sursa(job #3210681)

Utilizator luca.pislaruAho.Corasike luca.pislaru Data 7 martie 2024 08:30:48
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.54 kb
#include <fstream>
#include <cstring>
using namespace std;
ifstream cin("evaluare.in");
ofstream cout("evaluare.out");
int st1[100001];
int st2[100001];
char ch[100001];
int calc(int x, int y, int op)
{
	if(op==-1)
		return x+y;
	else
	if(op==-2)
		return x-y;
	else
	if(op==-3)
		return x*y;
	else
		return x/y;
}
int main()
{
    int l, poz1=0, poz2=0, i, ok=0, nr=0;
	cin>>ch;
	l=strlen(ch);
	for(i=0;i<l;i++)
	{
		if(ch[i]>='0'&&ch[i]<='9')
		{
			ok=1;
			nr=nr*10+ch[i]-'0';
		}
		else
		{
			if(ok==1)
			{
				ok=0;
				st1[++poz1]=nr;
				nr=0;
			}
			if(ch[i]=='(')
				st2[++poz2]=0;
			else
			if(ch[i]==')')
			{
				while(st2[poz2]<0)
				{
					st1[poz1-1]=calc(st1[poz1-1],st1[poz1],st2[poz2]);
					poz1--;
					poz2--;
				}
				poz2--;
			}
			else
			if(ch[i]=='+'||ch[i]=='-')
			{
				while(poz2>0&&st2[poz2]<0)
				{
					st1[poz1-1]=calc(st1[poz1-1],st1[poz1],st2[poz2]);
					poz1--;
					poz2--;
				}
				poz2++;
				if(ch[i]=='+')
					st2[poz2]=-1;
				else
					st2[poz2]=-2;
			}
			else
			{
			    while(poz2>0&&(st2[poz2]==-3||st2[poz2]==-4))
				{
				    ///cout<<st2[k2]<<" ";
					st1[poz1-1]=calc(st1[poz1-1],st1[poz1],st2[poz2]);
					poz1--;
					poz2--;
				}
				if(ch[i]=='*')
					st2[++poz2]=-3;
				else
					st2[++poz2]=-4;
			}
		}
	}
	if(ok==1)
    {
		st1[++poz1]=nr;
    }
	while(poz2>0)
	{
	   /// cout<<st2[k2]<<" ";
		st1[poz1-1]=calc(st1[poz1-1],st1[poz1],st2[poz2]);
		poz1--;
		poz2--;
	}
	cout<<st1[1];
    return 0;
}