Cod sursa(job #326674)

Utilizator crisojogcristian ojog crisojog Data 25 iunie 2009 19:31:28
Problema Evaluarea unei expresii Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 2.61 kb
#include<stdio.h>  
#include<string.h> 
#include<ctype.h>
char s[100010],polo[100010][12],op[100010];
int ps[100010];
long i,j,l,t;
int prior(char a)
{
	if(a=='+' || a=='-') return 1;
	return 2;
}
int main()
{
	freopen("evaluare.in","r",stdin);
	freopen("evaluare.out","w",stdout);
	gets(s);
	l=strlen(s);
	for(i=0;i<l;++i)
	{ 
		if(isdigit(s[i]))
		{
			polo[0][1]++;
			polo[polo[0][1]][++t]=s[i];
			while(isdigit(s[i+1]))
			{
				i++;
				polo[polo[0][1]][++t]=s[i];
			}
			polo[polo[0][1]][0]=t;
			t=0;
		}
		else
		{
			if(!op[0] || s[i]=='(')
			{
				++op[0];
				op[op[0]]=s[i];
			}
			else 
			{			
				if(s[i]==')')
				{
					while(op[op[0]]!='(')
					{
						polo[++polo[0][1]][1]=op[op[0]];
						polo[polo[0][1]][0]=1;
						op[0]--;
					}
					op[0]--;
				}
				else
				{
					if(prior(op[op[0]])<prior(s[i]) || op[op[0]]=='(')
					{
						op[++op[0]]=s[i];
					}
					else
					{
						while(op[0] && op[op[0]]!='(')
						{
							polo[++polo[0][1]][1]=op[op[0]];
							polo[polo[0][1]][0]=1;
							op[0]--;
						}
						op[++op[0]]=s[i];
					}
				}
			}
		}
	}
	while(op[0])
	{
		polo[++polo[0][1]][1]=op[op[0]];
		polo[polo[0][1]][0]=1;
		op[0]--;
	}
/*	for(i=1;i<=polo[0][1];++i)
	{
		for(j=1;j<=polo[i][0];++j)
		{
			printf("%c",polo[i][j]);
		}
		printf("\n");
	}*/
	t=1;
	long a,b,c,temp[12];
	
	while(t)
	{
		t=0;
		for(i=1;i<=polo[0][1];++i)
		{
			if(!isdigit(polo[i][1]) && polo[i][1]!=NULL)
			{	
				t=1;
				a=b=0;
				for(j=1;j<=polo[i-2][0];++j)
					a=a*10+(polo[i-2][j]-'0');
				if(ps[i-2]) a*=-1;
				if(polo[i-2][1]==NULL) a=0;
				for(j=1;j<=polo[i-1][0];++j)
					b=b*10+(polo[i-1][j]-'0');
				if(ps[i-1]) b*=-1;
				if(polo[i-1][1]==NULL) b=0;
				if(polo[i][1]=='+') c=a+b;
					else 
						if(polo[i][1]=='-') c=a-b;
							else 
								if(polo[i][1]=='*') c=a*b;
									else 
										if(polo[i][1]=='/') c=a/b;
				memset(temp,0,sizeof(temp));
				if(c<0)
				{
					ps[i-2]=1;
					c*=-1;
				} 
				else ps[i-2]=0;
				if(!c) polo[i-2][1]=0,polo[i-2][0]=1,ps[i-2]=0;
				else
				{
					while(c)
					{
						temp[++temp[0]]=c%10;
						c=c/10;
					}
					for(j=1;j<=temp[0];++j)
						polo[i-2][j]=temp[temp[0]-j+1]+'0';
					polo[i-2][0]=temp[0];
				}
				for(j=i-1;j<=polo[0][1]-2;++j)
				{
					strcpy(polo[j],polo[j+2]);
					ps[j]=ps[j+2];
				}
				polo[0][1]-=2;
				break;
			}
		}
	}
	if(ps[1]) printf("-");
	for(i=1;i<=polo[1][0];++i)
	{
		if(!polo[1][i]) printf("0");
			else		
				printf("%c",polo[1][i]);
	}
	printf("\n");
	return 0;
}