Pagini recente » Cod sursa (job #1668287) | Cod sursa (job #170704) | Cod sursa (job #2476361) | Cod sursa (job #1419153) | Cod sursa (job #1503594)
#include <cstdio>
#include <stack>
#include <fstream>
#include <cstdlib>
#include <cstring>
using namespace std;
const int nmx = 100002;
ifstream f("evaluare.in");
ofstream o("evaluare.out");
char s[nmx];
stack <int> stn;
stack <char> sts;
int grad(const char c) {
if(c == '(' || c == ')')
return 0;
if(c == '+' || c == '-')
return 1;
return 2;
}
int calcul(int nr1, int nr2, char semn) {
if(semn == '+')
return nr1 + nr2;
if(semn == '-')
return nr1 - nr2;
if(semn == '*')
return nr1 * nr2;
return nr1 / nr2;
}
void evaluare() {
size_t m = strlen(s);
s[m++] = ')';
char semn;
int nr1,nr2;
sts.push('(');
for(size_t i = 0; i < m; ++i) {
if(s[i] == '(') {
sts.push('(');
continue;
}
if(isdigit(s[i])) {
int nr = 0;
while(isdigit(s[i])) {
nr = nr * 10 + (int)s[i] - 48;
++ i;
}
stn.push(nr);
-- i;
continue;
}
if(s[i] == ')') {
while(sts.size() && sts.top() != '(') {
semn = sts.top();
sts.pop();
nr2 = stn.top();
stn.pop();
nr1 = stn.top();
stn.pop();
stn.push(calcul(nr1,nr2,semn));
}
continue;
}
while(sts.size() && grad(s[i]) <= grad(sts.top())) {
semn = sts.top();
sts.pop();
nr2 = stn.top();
stn.pop();
nr1 = stn.top();
stn.pop();
stn.push(calcul(nr1,nr2,semn));
}
sts.push(s[i]);
}
}
int main() {
f >> s;
evaluare();
o << stn.top();
return 0;
}