Cod sursa(job #465543)

Utilizator SmarandaMaria Pandele Smaranda Data 24 iunie 2010 18:02:37
Problema Evaluarea unei expresii Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.95 kb
#include<stdio.h>
#include<math.h>
#include<string.h>
char s[100001];
char polo[100001][11];
char op[100001];
long st[100001];
long p;
long prioritate(char x)
{
	if (x=='*' || x=='/')
		return 2;
	else
		return 1;
}

void poz (long k)
{
	long i;
	for (i=k;i<=p;i++)
		memcpy(polo[i-2],polo[i],sizeof(polo[i-2]));
	p=p-2;
}


int main()
{
	long n,i,u,nr,k,pri1,pri2,nr1,nr2,j,nr3,cif,a;
	
	freopen("evaluare.in","r",stdin);
	freopen("evaluare.out","w",stdout);
	
	gets(s);
	n=strlen(s);
	p=u=0;
	i=0;
	while (i<n)
	{
		if (s[i]-48>=0 && s[i]-48<=9)
		{
			p++;
			k=0;
		    polo[p][  ++ k   ]=s[i];
			while (1)
			{
				i++;
				if (!(s[i]-48>=0 && s[i]-48<=9) )
					break;
				polo[p][++k]=s[i];
			}
			polo[p][k+1]=NULL;
			polo[p][0]='+';
		}
		
		
		if (s[i]=='(')
			op[++u]='(';
		if (s[i]==')')
		{
			while (op[u]!='(')
			{
				
				polo[++p][1]=op[u];
				u--;
			}
			u--;
		}
		if (s[i]=='+' || s[i]=='-' || s[i]=='*' || s[i]=='/')
		{
			pri1=prioritate(op[u]);
			pri2=prioritate(s[i]);
			if (pri1>pri2)
			{
				while (pri1>pri2)
				{
					polo[++p][1]=op[u];
					u--;
					pri1=prioritate(op[u]);
				}
				op[++u]=s[i];
			}
			else
			{
				op[++u]=s[i];
			}
		}
		i++;
	}
	while (u)
			{
				if (op[u]!='(')
				polo[++p][1]=op[u];
				u--;
			}
    for (i= 1;i<=p;i++)
	{
		if (polo[i][1]-48>=0 && polo[i][1]-48<=9)
		{
			a=0;
			n=strlen(polo[i]);
			for (j=1;j<n;j++)
				a=a*10+polo[i][j]-48;
			if (polo[i][0]=='-')
				a=a*(-1);
			st[++st[0]]=a;
		}
		else
		{
			if (st[0]!=1)
			{
			if (polo[i][1]=='+')
				st[st[0]-1]=st[st[0]-1]+st[st[0]];
			else
				if (polo[i][1]=='-')
					st[st[0]-1]=st[st[0]-1]-st[st[0]];
				else
					if (polo[i][1]=='*')
						st[st[0]-1]=st[st[0]-1]*st[st[0]];
					else
						if (polo[i][1]=='/')
							st[st[0]-1]=st[st[0]-1]/st[st[0]];
			st[0]--;
			}
		}
	}
	
	printf("%ld",st[st[0]]);
	return 0;
}