Pagini recente » Cod sursa (job #1145319) | Cod sursa (job #3467) | Cod sursa (job #828682) | Cod sursa (job #2597295) | Cod sursa (job #355900)
Cod sursa(job #355900)
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <assert.h>
#define MAXSIZE 150002
using namespace std;
int main() {
ifstream cin("evaluare.in");
ofstream cout("evaluare.out");
string s;
cin >> s;
char interStack[MAXSIZE], postfix[MAXSIZE];
int computing[MAXSIZE];
int i, ni, np = 0, ic;
// To postfix
ni = 0;
interStack[0] = '\0';
for (i = 0; i <= s.length(); i++) {
if (s[i] >= '0' && s[i]<= '9') {
while (s[i] >= '0' && s[i]<= '9') {
postfix[np] = s[i];
np++;
i++;
}
i--;
postfix[np] = '\0';
np++;
} else if ((s[i] == '*' || s[i] == '/') && (interStack[ni] == '*' || interStack[ni] == '/')) {
postfix[np] = interStack[ni];
np++;
ni--;
i--;
} else if ((s[i] == '+' || s[i] == '-') && (interStack[ni] == '+' || interStack[ni] == '-' || interStack[ni] == '*' || interStack[ni] == '/')) {
postfix[np] = interStack[ni];
np++;
ni--;
i--;
} else if (s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/' || s[i] == '(') {
ni++;
interStack[ni] = s[i];
} else if (s[i] == ')') {
while (interStack[ni] != '(') {
postfix[np] = interStack[ni];
np++;
ni--;
}
ni--;
} else if (s[i] == '\0') {
while (interStack[ni] != '\0') {
postfix[np] = interStack[ni];
np++;
ni--;
}
}
}
// for (i = 0; i < np; i++) {
// cout << postfix[i];
// }
// cout << '\n';
int numStart;
ic = -1;
for (i = 0; i < np; i++) {
if (postfix[i] >= '0' && postfix[i] <= '9') {
numStart = i;
while (postfix[i] >= '0' && postfix[i] <= '9') {
i++;
}
assert(postfix[i] == '\0');
ic++;
computing[ic] = atoi(&postfix[numStart]);
} else if (postfix[i] == '+') {
ic--;
computing[ic] += computing[ic + 1];
} else if (postfix[i] == '-') {
ic--;
computing[ic] -= computing[ic + 1];
} else if (postfix[i] == '*') {
ic--;
computing[ic] *= computing[ic + 1];
} else if (postfix[i] == '/') {
ic--;
computing[ic] /= computing[ic + 1];
}
}
cout << computing[0];
cout.close();
return 0;
}