Cod sursa(job #1418286)

Utilizator andreiagAndrei Galusca andreiag Data 12 aprilie 2015 16:42:02
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.53 kb
// reverse polish notation
#include <iostream>
#include <fstream>
#include <string>
#include <stack>
#include <vector>
#include <algorithm>
#include <cctype>

using namespace std;

inline bool is_op(char c) {
  return c == '+' || c == '-' || c == '*' || c == '/';
}

void calc(stack<int> &st, char semn) {
  int y = st.top(); st.pop();
  int x = st.top(); st.pop();
  int z = 0;
  switch (semn) {
    case '+': z = x+y; break;
    case '-': z = x-y; break;
    case '*': z = x*y; break;
    case '/': z = x/y; break;
  }
  st.push(z);
}

int oper_ord(char c) {
  if (c == '+' || c == '-') return 1;
  if (c == '*' || c == '/') return 2;
  return -1;
}

int main()
{
  ifstream f ("evaluare.in");
  ofstream g ("evaluare.out");
  string A;
  f >> A;
  stack<int> num;
  stack<char> oper;
  for (int i = 0; i < A.size(); i++) {
    char c = A[i];
    if (c == '(') {
      oper.push(c);
      continue;
    }
    if (c == ')') {
      while (oper.top() != '(') {
        calc(num, oper.top());
        oper.pop();
      }
      oper.pop(); // remove the '(';
      continue;
    }
    if (is_op(c)) {
      while(!oper.empty() && oper_ord(oper.top()) >= oper_ord(c)) {
        calc(num, oper.top());
        oper.pop();
      }
      oper.push(c);
      continue;
    }
    if (isdigit(c)) {
      int operand = 0;
      while(i < A.size() && isdigit(A[i])) {
        operand = operand*10 + A[i] - '0';
        i++;
      }
      --i;
      num.push(operand);
    }
  }
  while (!oper.empty()) {
    calc(num, oper.top());
    oper.pop();
  }
  g << num.top() << '\n';
}