Pagini recente » Cod sursa (job #3232070) | Cod sursa (job #347227) | Cod sursa (job #2962125) | Cod sursa (job #3032477) | Cod sursa (job #3274254)
#include <bits/stdc++.h>
using namespace std;
const string nume="evaluare";
ifstream f(nume+".in");
ofstream g(nume+".out");
enum tip {
NUMAR, OPERATOR, PAR
};
struct Token {
tip type;
int value;
char op;
Token(int v) : type(NUMAR), value(v), op(0) {}
Token(char c, tip t) : type(t), value(0), op(c) {}
};
int precedence(char op)
{
if (op == '*' || op == '/')
return 2;
if (op == '+' || op == '-')
return 1;
return 0;
}
int main(){
ios::sync_with_stdio(false);
f.tie(nullptr);
string expr;
getline(f, expr);
vector<Token> tokens;
for (size_t i = 0; i < expr.size(); )
{
if (isspace(expr[i]))
i++;
else if (isdigit(expr[i]))
{
int num = 0;
while (i < expr.size() && isdigit(expr[i]))
{
num = num * 10 + (expr[i] - '0');
i++;
}
tokens.push_back(Token(num));
}
else
{
char c = expr[i];
if (c == '+' || c == '-' || c == '*' || c == '/')
tokens.push_back(Token(c, OPERATOR));
else if (c == '(' || c == ')')
tokens.push_back(Token(c, PAR));
i++;
}
}
vector<Token> output;
stack<Token> opStack;
for (auto &t : tokens)
{
if (t.type == NUMAR)
output.push_back(t);
else if (t.type == OPERATOR)
{
while (!opStack.empty() && opStack.top().type == OPERATOR &&
precedence(opStack.top().op) >= precedence(t.op))
{
output.push_back(opStack.top());
opStack.pop();
}
opStack.push(t);
}
else if (t.type == PAR)
{
if (t.op == '(')
opStack.push(t);
else if (t.op == ')')
{
while (!opStack.empty() && !(opStack.top().type == PAR && opStack.top().op == '('))
{
output.push_back(opStack.top());
opStack.pop();
}
if (!opStack.empty())
opStack.pop();
else
assert(false);
}
}
}
while (!opStack.empty())
{
output.push_back(opStack.top());
opStack.pop();
}
stack<int> evalStack;
for (auto &t : output)
{
if (t.type == NUMAR)
evalStack.push(t.value);
else if (t.type == OPERATOR)
{
int b = evalStack.top();
evalStack.pop();
int a = evalStack.top();
evalStack.pop();
int res = 0;
if(t.op=='+') res = a + b;
else if(t.op=='-') res = a - b;
else if(t.op=='*') res = a * b;
else if(t.op=='/') res = a / b;
evalStack.push(res);
}
}
int result = evalStack.top();
g << result;
return 0;
}