Cod sursa(job #682446)

Utilizator noruIlies Norbert noru Data 18 februarie 2012 23:32:39
Problema Evaluarea unei expresii Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.11 kb
#include<stdio.h>
#include<ctype.h>
FILE *f=fopen("expresie.in","r");
FILE *g=fopen("expresie.out","w");
int main()
{
	int st[100001],vf=0,v[100001],ok=1,nr,n=0,i;
	char c;
	while (!feof(f))
	{
		if (ok==1)
			fscanf(f,"%c",&c);
		ok=1;
		if (isdigit(c))
		{
			nr=0;
			while (isdigit(c))
			{
				nr=nr*10+c-'0';
				fscanf(f,"%c",&c);
			}
			ok=0;
			v[++n]=nr;
		}
		else
		{
			if (c=='*') st[++vf]=1;
			if (c=='/') st[++vf]=2;
			if (c=='+') 
			{
				while (st[vf]<=2&&vf>0)
					v[++n]=st[vf--]*-1;
				st[++vf]=3;
			}
			if (c=='-') 
			{
				while (st[vf]<=2&&vf>0)
					v[++n]=st[vf--]*-1;			
				st[++vf]=4;
			}
			if (c=='(') st[++vf]=5;
			if (c==')')
			{
				while (st[vf]!=5&&vf>0)
					v[++n]=st[vf--]*-1;
				vf--;
			}
		}
	}
	while (vf!=0)
		v[++n]=st[vf--]*-1;
	for (i=1;i<=n;i++)
		if (v[i]>=0) st[++vf]=v[i];
		else
		{
			if (v[i]==-1){st[vf-1]=st[vf]*st[vf-1];}
			if (v[i]==-2){st[vf-1]=st[vf-1]/st[vf];}
			if (v[i]==-3){st[vf-1]=st[vf]+st[vf-1];}
			if (v[i]==-4){st[vf-1]=st[vf-1]-st[vf];}vf--;
		}
	fprintf(g,"%d",st[1]);
	return 0;
}