Cod sursa(job #579531)

Utilizator SmarandaMaria Pandele Smaranda Data 12 aprilie 2011 11:05:38
Problema Evaluarea unei expresii Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 2.51 kb
#include<stdio.h>
#include<string.h>
char s[100011];
char polo[100011];
char op[100011];
long f[255];
long n;
void stanga (long a, long b)
{
	long i;
	for (i=a;i<n;i++)
		s[i]=s[i+b-a];
	n=n-b+a;
}

void stangap (long a, long b)
{
	long i;
	for (i=a;i<polo[0];i++)
		polo[i]=polo[i+2];
	polo[0]=polo[0]-2;
}



int main()
{
	long i,nr=0,j,l=0;
	
	freopen("evaluare.in","r",stdin);
	freopen("evaluare.out","w",stdout);
	
	gets(s);
	n=strlen(s);
	i=0;
	while (i<n)
	{
		if (s[i]>='0' && s[i]<='9')
		{
			nr=0;
			j=i;
			while (s[i]>='0' && s[i]<='9')
			{
				nr=nr*10+s[i]-48;
				i++;
			}
			s[j]=++f[0]+'a'-1;
			f[f[0]]=nr;
			stanga(j+1,i);
			i=j+1;
		}
		i++;
	}
	
	i=0;
	while (i<n)
	{
		if (s[i]=='(')
		{
			l=0;
			j=i;
			while (s[i]!=')')
			{
				l++;
				i++;
			}
			if (l==3)
			{
				if (s[j+1]=='-')
					f[s[j+2]-'a'+1]=f[s[j+2]-'a'+1]*(-1);
				stanga(j,j+2);
				stanga(j+1,n);
			}
		}
		i++;
	}
	
	for (i=0;i<n;i++)
	{
		if (s[i]=='(')
			op[++op[0]]=s[i];
		if (s[i]=='+' || s[i]=='-')
		{
			if (op[op[0]]!='*' && op[op[0]]!='/')
				op[++op[0]]=s[i];
			else
			{
				while ((op[op[0]]=='*' || op[op[0]]=='/') && op[0])
				{
					polo[++polo[0]]=op[op[0]];
					op[0]--;
				}
				op[++op[0]]=s[i];
			}
		}
		if (s[i]=='*' || s[i]=='/')
		{
			if (s[i]=='+' || s[i]=='-')
				op[++op[0]]=s[i];
			else
			{
				while ((op[op[0]]=='*' || op[op[0]]=='/') && op[0])
				{
					polo[++polo[0]]=op[op[0]];
					op[0]--;
				}
				op[++op[0]]=s[i];
			}
		}
		if (s[i]>='a' && s[i]<='z')
			polo[++polo[0]]=s[i];
		if (s[i]==')')
		{
			while (op[op[0]]!='(' && op[0])
			{
				polo[++polo[0]]=op[op[0]];
				op[0]--;
			}
			op[0]--;
		}
	}
	while (op[0])
	{
		polo[++polo[0]]=op[op[0]];
		op[0]--;
	}
	i=1;
	while (polo[0]>1)
	{
		if (!(polo[i]>='a' && polo[i]<='z'))
		{
			if (polo[i]=='+')
			{
				f[++f[0]]=f[polo[i-1]-'a'+1]+f[polo[i-2]-'a'+1];
				polo[i-2]=f[0]+'a'-1;
				stangap(i-1,i-1);
			}
			if (polo[i]=='-')
			{
				f[++f[0]]=f[polo[i-2]-'a'+1]-f[polo[i-1]-'a'+1];
				polo[i-2]=f[0]+'a'-1;
				stangap(i-1,i-1);
			}
			if (polo[i]=='*')
			{
				f[++f[0]]=f[polo[i-1]-'a'+1]*f[polo[i-2]-'a'+1];
				polo[i-2]=f[0]+'a'-1;
				stangap(i-1,i-1);
			}
			if (polo[i]=='/')
			{
				f[++f[0]]=f[polo[i-2]-'a'+1]/f[polo[i-1]-'a'+1];
				polo[i-2]=f[0]+'a'-1;
				stangap(i-1,i-1);
			}
		i=1;
		}
		else
			i++;
	}
	printf("%ld\n",f[polo[1]-'a'+1]);
	return 0;
}