Cod sursa(job #740751)

Utilizator mihaipopa12Popa Mihai mihaipopa12 Data 24 aprilie 2012 21:08:50
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.92 kb
#include<stdio.h>
#include<cstring>

#define maxdim 100005

FILE*f=fopen("evaluare.in","r");
FILE*g=fopen("evaluare.out","w");

int n,p;
int vf;
int postfix[maxdim],st[maxdim];
char sir[maxdim];

inline int get () {
	int r = 0;
	
	while ( sir[p] >= '0' && sir[p] <= '9' ){
		r = r * 10 + sir[p] - '0';
		++p;
	}
	
	return r;
}

inline bool op1 ( const char &x ){
	return x == '+' || x == '-';
}

inline bool op2 ( const char &x ){
	return x == '*' || x == '/';
}

int main () {
	
	fscanf(f,"%s",sir+1); n = strlen(sir+1);
	
	int u = 0;
	for ( p = 1 ; p <= n ; ){
		
		if ( sir[p] >= '0' && sir[p] <= '9' ){
			int x = get();
			postfix[++u] = x;
		}
		else{
			if ( sir[p] == '(' ){
				st[++vf] = '(';
			}
			else{
				if ( sir[p] == '+' || sir[p] == '-' ){
					while ( vf > 0 && (op1(st[vf]) || op2(st[vf])) ){
						postfix[++u] = -st[vf];
						st[vf] = 0; --vf;
					}
					st[++vf] = sir[p];
				}
				else{
					if ( sir[p] == '*' || sir[p] == '/' ){
						while ( vf > 0 && op2(st[vf]) ){
							postfix[++u] = -st[vf];
							st[vf] = 0; --vf;
						}
						st[++vf] = sir[p];
					}
					else{
						int ch;
						do{
							ch = st[vf]; if ( ch != '(' )	postfix[++u] = -ch;
							st[vf] = 0; --vf;
						}while(ch != '(');
					}
				}
			}
			++p;
		}
	}
	while ( vf ){
		postfix[++u] = -st[vf];
		st[vf] = 0; --vf;
	}
	
	vf = 0;
	for ( int i = 1 ; i <= u ; ++i ){
		
		if ( postfix[i] >= 0 ){
			st[++vf] = postfix[i];
		}
		else{
			int next;
			if ( postfix[i] == -'+' ){
				next = st[vf]+st[vf-1];
			}
			else{
				if ( postfix[i] == -'-' ){
					next = st[vf-1]-st[vf];
				}
				else{
					if ( postfix[i] == -'*' ){
						next = st[vf]*st[vf-1];
					}
					else{
						next = st[vf-1]/st[vf];
					}
				}
			}
			
			st[vf] = 0; --vf; st[vf] = next;
		}
	}
	
	fprintf(g,"%d\n",st[1]);
	
	fclose(f);
	fclose(g);
	
	return 0;
}