Pagini recente » Cod sursa (job #257423) | Cod sursa (job #2916972) | Cod sursa (job #2100286) | Cod sursa (job #3253990) | Cod sursa (job #2876079)
#include <iostream>
#include <stack>
#include <fstream>
#include <cstring>
#include <queue>
using namespace std;
const int mod = 1e9;
ifstream in("evaluare.in");
ofstream out("evaluare.out");
struct Stack{
queue<int> q1,q2;
void push(int x)
{
q2.push(x);
while(!q1.empty())
{
q2.push(q1.front());
q1.pop();
}
queue<int>q=q1;
q1=q2;
q2=q;
}
void pop()
{
if(!q1.empty())
q1.pop();
}
int top()
{
return q1.front();
}
bool empty()
{
return q1.empty();
}
}numbers,operators;
int precedence(char o) {
if (o == '*' || o == '/')
return 2;
if (o == '-' || o == '+')
return 1;
return 0;
}
int op(int a, int b, char o) {
switch (o) {
case '+':
return a + b;
case '-':
return a - b;
case '/':
return a / b;
case '*':
return a * b;
}
}
void apply(){
int val1 = numbers.top();
numbers.pop();
int val2=numbers.top();
numbers.pop();
numbers.push(op(val2, val1, operators.top()) % mod);
operators.pop();
}
int evaluate(char s[]) {
int l=strlen(s);
for (int i = 0; i < l; i++) {
if (s[i] >= '0' && s[i] <= '9') {
int n = 0, j;
for (j = i; s[j] <= '9' && s[j] >= '0'; j++)
n = n * 10 + s[j] - '0';
i = j - 1;
numbers.push(n);
}
else if (s[i] == '(')
operators.push('(');
else if (s[i] == ')') {
while (operators.top() != '(') {
apply();
}
operators.pop();
} else {
while (!operators.empty() && precedence(operators.top()) >= precedence(s[i])) {
apply();
}
operators.push(s[i]);
}
}
while (!operators.empty()) {
apply();
}
return numbers.top();
}
int main() {
char expr[100001];
in.getline(expr, 100001);
out<<evaluate(expr);
return 0;
}