Cod sursa(job #480458)

Utilizator Programmer01Mierla Laurentiu Marian Programmer01 Data 27 august 2010 22:25:59
Problema Evaluarea unei expresii Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.79 kb
#include<stdio.h>
#include<string.h>

char *a, *operatorStack;
int *operandStack, n, i1 = 0, i2 = 0;

int getPriority(char c){
	if(c == '*' || c == '/') return 2;
	if(c == '+' || c== '-') return 1;
	return 0;
}

void showOperandStack(){
	for(int i=0; i< i2; i++)
		printf("%i ", operandStack[i]);
	printf("\n");
}
void showOperatorStack(){
	for(int i=0; i< i1; i++)
		printf("%c ", operatorStack[i]);
	printf("\n");
}

void compute(char c){
	if(c == '(') return;
	int second = operandStack[--i2], first = operandStack[--i2];
	switch(c){
		case '+': operandStack[i2++] = first + second; break;
		case '-': operandStack[i2++] = first - second; break;
		case '*': operandStack[i2++] = first * second; break;
		default: operandStack[i2++] = first / second; break;
	}
}

void polishForm(){
	
	for(int i=0; i<n; i++) {
		if(a[i] == '(') operatorStack[i1++] = '(';
		else if(a[i] == ')')
			while(operatorStack[--i1] != '(')
				compute(operatorStack[i1]);
		else if(a[i] >= '0' && a[i] < '9') {
			int value = a[i] - 48;
			while(i < n-1 && a[i+1] >= '0' && a[i+1] <= '9') 
				value = value * 10 + a[++i] - 48;
			operandStack[i2++] = value;
		}
		else {
			int priority = getPriority(a[i]);
			while(i1 > 0 && getPriority(operatorStack[i1-1]) >= priority)
				compute(operatorStack[--i1]);
			operatorStack[i1++] = a[i];
		}
		
		showOperandStack();
		showOperatorStack();
	}
	
	while(i1>0){
		compute(operatorStack[--i1]);
	}
}

void read(){
	FILE *ifile;
	
	ifile = fopen("evaluare.in", "r");
	
	a = new char[100001];
	operatorStack = new char[100000];
	operandStack = new int[100000];
	fscanf(ifile, "%s", a);	
	n = strlen(a);

	fclose(ifile);
}

void write(){
	FILE *ofile;

	ofile = fopen("evaluare.out", "w");
	fprintf(ofile, "%li\n", operandStack[0]);

	fclose(ofile);
}


int main()
{
	read();
	polishForm();
	write();
	return 0;
}