Cod sursa(job #2536660)

Utilizator sygAndreiIonitaIonita Andrei sygAndreiIonita Data 2 februarie 2020 14:06:35
Problema Evaluarea unei expresii Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.64 kb
#include <fstream>
#include <stack>
#include <cctype>

using namespace std; 

ifstream in ("evaluare.in");
ofstream out ("evaluare.out");

stack <char> s;
stack <long long> fin;
char v[100001];

short int smecherie (char c)
{
  if (c=='*'||c=='/')
    return 1;
  else if (c=='(')
    return 0;
  else 
    return 2;  
}

bool is_digit(char c)
{
  if (c<='9'&&c>='0')
   return 1;
  return 0;
}

int main()
{
  char c,aux='a';
  long long cnt=0,nr,x1,x2,r;
  while (in.get(c)&&c!='\n')
  {
    if (!isdigit(c)&&isdigit(aux))
      v[++cnt]=' ';
    if (c<='9'&&c>='0')
      v[++cnt]=c;
    else if (c==')')
    {
      while (!s.empty()&&s.top()!='(')
        v[++cnt]=s.top(),s.pop();
      s.pop();
    }
    else if (c=='(')
      s.push(c);
    else if (c=='+'||c=='-')
    {
      while (!s.empty()&&smecherie(s.top())>=1)
        v[++cnt]=s.top(),s.pop();
      s.push(c);
    }
    else
    {
      while (!s.empty()&&smecherie(s.top())==1)
        v[++cnt]=s.top(),s.pop();
      s.push(c);
    }
    aux=c;
  }
  aux='a';
  while (!s.empty())
    v[++cnt]=s.top(),s.pop();
  for (int i=1;i<=cnt;i++)
  {
    if (is_digit(v[i])&&!is_digit(aux))
      nr=v[i]-48;
    else if (is_digit(v[i])&&is_digit(aux))
      nr=nr*10+v[i]-48;
    else if (!isdigit(v[i]))
    {
      if (isdigit(aux))  
        fin.push(nr);
      if (v[i]!=' ')
      {
        x1=fin.top(),fin.pop(),x2=fin.top(),fin.pop();
        if (v[i]=='+')
          r=x1+x2;
        else if (v[i]=='-')
          r=x2-x1;
        else if (v[i]=='*')
          r=x2*x1;
        else if (v[i]=='/')
          r=x2/x1;
        fin.push(r);   
      }
    }
    aux=v[i];
  }
  out<<fin.top();
  return 0;
}