Pagini recente » Cod sursa (job #308463) | Cod sursa (job #1379014) | Cod sursa (job #3135957) | Cod sursa (job #2177292) | Cod sursa (job #480461)
Cod sursa(job #480461)
#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 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];
}
}
while(i1>0){
compute(operatorStack[--i1]);
}
}
void read(){
FILE *ifile;
ifile = fopen("evaluare.in", "r");
a = new char[100005];
operatorStack = new char[100005];
operandStack = new int[100005];
fscanf(ifile, "%s", a);
n = strlen(a);
fclose(ifile);
}
void write(){
FILE *ofile;
ofile = fopen("evaluare.out", "w");
fprintf(ofile, "%i\n", operandStack[0]);
fclose(ofile);
}
int main()
{
read();
polishForm();
write();
return 0;
}