Cod sursa(job #2239562)

Utilizator mihaimusat.1998Musat Mihai-Robert mihaimusat.1998 Data 11 septembrie 2018 09:42:45
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.1 kb
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<vector>
#include<map>
#include<stack>
#include<queue>

#define MAX_LEN 100005

int doArithmetic(int left,int right,char operation) {

	switch(operation) {
		case '+':
			return left+right;
		case '-':
			return left-right;
		case '*':
			return left*right;
		case '/':
			return left/right;
		default:
			return 0;
	}

}

void applyOperation(std::stack<int>& numbers,std::stack<char>& operators) {

	int right=numbers.top();
	numbers.pop();

	int left=numbers.top();
	numbers.pop();

    char operation=operators.top();

	int tmp=doArithmetic(left,right,operation);
	operators.pop();

	numbers.push(tmp);

}

int getPrecedence(char operation) {

    if(operation=='+' || operation=='-')
        return 1;
    if(operation=='*' || operation=='/')
        return 2;
    else
        return 0;

}

bool hasPrecedence(char a,char b) {

	return getPrecedence(a)>=getPrecedence(b);

}


int evalExpr(char *str) {

	std::stack<int> numbers;
	std::stack<char> operators;

	if(!str)
		return -1;

	int len=strlen(str);
	for(int i=0;i<len;i++) {

        char ch=str[i];

		if(ch=='(')
			operators.push(ch);

		else if(ch>='0' && ch<='9') {
			int value=0;
			for(int j=i;str[j]>='0' && str[j]<='9';j++) {
				value=value*10+(str[j]-'0');
				i=j;
			}
			numbers.push(value);
		}

		else if(ch==')') {
			while(!operators.empty() && operators.top()!='(') {
				applyOperation(numbers,operators);
			}
			operators.pop();
		}

		else {
			while(!operators.empty() && hasPrecedence(operators.top(),ch)) {
				applyOperation(numbers,operators);
			}
			operators.push(ch);
		}
	}

	while(!operators.empty()) {
		applyOperation(numbers,operators);
	}

	return numbers.top();

}

int main()
{
	FILE *fin,*fout;
	fin=fopen("evaluare.in","r");
	fout=fopen("evaluare.out","w");

	char str[MAX_LEN];

	fscanf(fin,"%s",str);
	int result=evalExpr(str);
	fprintf(fout,"%d\n",result);

	fclose(fin);
	fclose(fout);

	return 0;
}