Cod sursa(job #465533)

Utilizator SmarandaMaria Pandele Smaranda Data 24 iunie 2010 17:09:31
Problema Evaluarea unei expresii Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.29 kb
#include<stdio.h>
#include<math.h>
#include<string.h>
char s[100001];
char polo[100001][11];
char op[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;
	
	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--;
			}
		}
		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>1)
			{
				
				polo[++p][1]=op[u];
				u--;
			}
    while (p>1)
	{
		for (i=1;i<=p;i++)
			if (polo[i][1]=='+' || polo[i][1]=='-' || polo[i][1]=='*' || polo[i][1]=='/')
			{
				nr1=nr2=0;
				n=strlen(polo[i-2]);
				for (j=1;j<n;j++)
				{
					nr2=nr2*10+polo[i-2][j]-48;
				}
				if (polo[i-2][0]=='-')
					nr2=nr2*(-1);
				n=strlen(polo[i-1]);
				for (j=1;j<n;j++)
				{
					nr1=nr1*10+polo[i-1][j]-48;
				}
				if (polo[i-1][0]=='-')
					nr1=nr1*(-1);
				if (polo[i][1]=='+')
					nr3=nr2+nr1;
				if (polo[i][1]=='-')
					nr3=nr2-nr1;
				if (polo[i][1]=='*')
					nr3=nr2*nr1;
				if (polo[i][1]=='/')
					nr3=nr2/nr1;
				cif=log10(nr3)+1;
				if (nr3<0)
					polo[i-2][0]='-';
				else
					polo[i-2][0]='+';
				for (j=cif;j>=1;j--)
					{
						polo[i-2][j]=nr3%10+48;
						nr3=nr3/10;
					}
			    polo[i-2][cif+1]=NULL;
				poz(i+1);
			}
	}
	n=strlen(polo[1]);
	if (polo[1][0]=='-')
		for (i=0;i<n;i++)
			printf("%c",polo[1][i]);
	else
		for (i=1;i<n;i++)
			printf("%c",polo[1][i]);
	return 0;
}