Cod sursa(job #1798269)

Utilizator MKLOLDragos Ristache MKLOL Data 5 noiembrie 2016 07:13:13
Problema Evaluarea unei expresii Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.63 kb
#include<bits/stdc++.h>
#define pb push_back
using namespace std;
typedef long long ll;
#define fs first
#define sc second
#define mp make_pair
string gb;
int getnum(int st,int dr) {
  int ret = 0;
  for(int i=st;i<=dr;++i) {
    ret *= 10;
    ret += (gb[i] -'0');
  }
  return ret;
}

vector<vector<string>> ops;
// is operation op, at location loc, when the string is st,dr
int is(string op, int loc,int st,int dr) {
  if(loc + op.size() - 1 > dr) return 0;
  int ok = 1;
  for(int i=0;i<op.size() && ok;++i) {
    if(gb[i+loc] != op[i]) ok = 0;
  }
  return ok;
}

int make(string op,int x,int y) {
  if(op == "-") return x-y;
  if(op == "+") return x+y;
  if(op == "%") return x%y;
  if(op == "/") return x/y;
  if(op == "*") return x*y;
}

int eval(int st,int dr, int lvl) {
  for(int t = lvl;t<ops.size();++t) {
      int par = 0;
      for(int i = dr;i>=st;--i) {
        if(gb[i] == '(') ++ par;
        if(gb[i] == ')') -- par;
        if(par) continue;
        
        for(auto op : ops[t]) {
          if(is(op,i,st,dr)) {
            return make(op,eval(st,i-1,t),eval(i+op.size(),dr,t));
          }
        }
      }
  }
  if(gb[st] == '(') {
    return eval(st+1,dr-1,0);
  }
  return getnum(st,dr);
}
//add operations in order
void init() {
  ops.pb(vector<string>({"+","-"}));
  ops.pb(vector<string>({"/","%","*"}));
}
int eval(string &s) {
  gb = "";
  for(auto c : s) {
    if(c != ' ') gb.pb(c);
  }
  int ret = eval(0,gb.size()-1,0);
  return ret;
}
string s;
int main() {
  freopen("evaluare.in","r",stdin);
  freopen("evaluare.out","w",stdout);
  init();
  cin.sync_with_stdio(false);
  getline(cin,s);
  cout << eval(s) << "\n";
  
  return 0;
}