Cod sursa(job #912854)

Utilizator alexandru70Ungurianu Alexandru alexandru70 Data 12 martie 2013 20:45:47
Problema Evaluarea unei expresii Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 2.15 kb
#include <fstream>
#include <string>
#include <stack>
#include <map>
using namespace std;
ifstream in ("evaluare.in"); ofstream out ("evaluare.out");

map<char,short> pri;

string Conv(string e)
{
  string res;
  stack<char> ops;
  for(int i = 0; i < e.size(); ++i)
  {
    if(e[i]<='9' && e[i]>='0' )
    {
      if(!e.empty())
      {
        if(!(e[i-1]<='9' && e[i-1]>='0' ))
        {
          res.push_back(' ');
        }
      }
      res.push_back(e[i]);
    }
    else if(e[i]==')')
    {
      while(ops.top()!='(')
      {
        res.push_back(' ');
        res.push_back(ops.top());
        ops.pop();
      }
      ops.pop();
    }
    else
    {
      if(e[i]=='('){ops.push(e[i]); continue;};
      if(ops.empty())
      {
        ops.push(e[i]);
        continue;
      }
      if(pri[e[i]]<=pri[ops.top()])
      {
        res.push_back(' ');
        res.push_back(ops.top());
        ops.pop();
        ops.push(e[i]);
      }
      else
      {
        ops.push(e[i]);
      }
    }
  }
  while(!ops.empty())
  {
    res.push_back(' ');
    res.push_back(ops.top());
    ops.pop();
  }
  return res;
}

int resolve(string e)
{
  stack<int> s;
  for(int i = 1; i < e.size(); i+=2)
  {
    if(e[i]>='0' && e[i]<='9')
    {
      int x = 0;
      while(e[i]!=' ')
      {
        x=x*10+(e[i]-'0');
        i++;
      }
      s.push(x);
      --i;
    }
    else
    {
      int a,b;
      switch(e[i])
      {
        case '+':
          a=s.top();s.pop();
          b=s.top();s.pop();
          s.push(a+b);break;
        case '-':
          a=s.top();s.pop();
          b=s.top();s.pop();
          s.push(b-a);break;
        case '*':
          a=s.top();s.pop();
          b=s.top();s.pop();
          s.push(a*b);break;
        case '/':
          a=s.top();s.pop();
          b=s.top();s.pop();
          s.push(b/a);break;
      }
    }
  }
  return s.top();
}

string exp;

int main()
{
  pri['-']=1;
  pri['+']=1;
  pri['*']=2;
  pri['/']=2;
  pri['(']=-1;
  pri[')']=-1;
  in >> exp;
  string expConv = Conv(exp);

  out << resolve(expConv);
}