Cod sursa(job #332536)

Utilizator cvicentiuCiorbaru Vicentiu Marian cvicentiu Data 18 iulie 2009 15:02:25
Problema Evaluarea unei expresii Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 2.26 kb
#include <stdio.h>
#include <string>
#define MaxN 10015
FILE *f=fopen("evaluare.in","r");
FILE *g=fopen("evaluare.out","w");
char stack[MaxN];
int stack2[MaxN];
char s[MaxN],s2[MaxN],num[18];
long rez,temp;
long lung,vf,ind,ind2,nr;

void pop(){
	s2[ind] = stack[vf];
	--vf;
	++ind=ind;
	s2[ind] = ' ';
	++ind;
	
};

void push(char ch){
	stack[++vf] = ch;
};
void push2(int x){
	stack2[++vf] = x;
};

int main(){
	fgets(s,100010,f);
	lung=strlen(s);
	while (s[lung-1] == '\n' || s[lung-1] == ' ')
		lung--;
	vf = 0;
	ind = 0;
	for (int i = 0; i <= 10000; i++)
		s2[i] = ' ';
	for (int i = 0; i < lung;){
		switch(s[i]){
			case '(' :	push(s[i]);
						++i;
						break;

			case '+' :	if ( stack[vf] != '(' && vf != 0) pop();
						else {
							push(s[i]);
							++i;
						};
						break;

			case '-' :	if ( stack[vf] != '(' && vf != 0) pop();
						else {
							push(s[i]);
							++i;
						};
						break;

			case '*' :	if ( stack[vf] == '/' || stack[vf] == '*' && vf != 0) pop();
						else {
							push(s[i]);
							++i;
						};
						break;

			case '/' :	if ( stack[vf] == '*' || stack[vf] == '/' && vf != 0) pop();
						else {
							push(s[i]);
							++i;
						};
						break;

			case ')' :	while (stack[vf] != '(')
							pop();
							
						--vf;
						++i;
						
						break;

			default :	
						s2[ind] = s[i];
						if ( !strchr("0123456789", s[i+1])){
							++ind;
							s2[ind] = ' ';
						};
						++ind;
						++i;
						

		};
	};
	while (vf != 0 ) pop();
	
	vf = 0;
	for (int i = 0; i <= ind; i++){
		if (strchr("0123456789", s2[i]) ){
		while (strchr("0123456789", s2[i]) ){
			
			num[ind2] = s2[i];		
			++i;
			++ind2;
			
		}
			nr = atoi(num);
			for (int j = 0; j <= 17; j++)
					num[j] = 0;
			ind2 = 0;
			push2(nr);
		};
		

		if (s2[i] == '+'){
			stack2[vf-1] += stack2[vf];
			--vf;
		}
		if (s2[i] == '-'){
			stack2[vf-1] -=stack2[vf];
			--vf;
		};
		if (s2[i] == '*'){
			stack2[vf-1] *= stack2[vf];
			--vf;
		};
		if (s2[i] == '/'){
			stack2[vf-1] /= stack2[vf];
			--vf;
		};
	};
	/*for (unsigned int i = 0; i <= ind ; i++)
		fprintf(g,"%c",s2[i]);*/
	fprintf(g,"%d",stack2[1]);
	fclose(f);
	fclose(g);
	return 0;
};