Cod sursa(job #2210698)

Utilizator cc4infinityCojocaru Catalin cc4infinity Data 7 iunie 2018 18:24:56
Problema Evaluarea unei expresii Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.68 kb
#include<bits/stdc++.h>
using namespace std;
const int nmax=1500000000;
string ex;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
int i;
int prec(char c)
{
    if(c == '^')
    return 3;
    else if(c == '*' || c == '/')
    return 2;
    else if(c == '+' || c == '-')
    return 1;
    else
    return -1;
}

string rev(string s)
{
    string s1;
    for (int i=s.size()-1;i>=0;i--)
        if (s[i]=='(') s1=s1+')'; else
           if (s[i]==')') s1=s1+'(';
               else s1=s1+s[i];
    return s1;
}

void itp(string s)
{
    stack<int> st;
    st.push('N');
    int l = s.length();
    string ns;
    for(int i = 0; i < l; i++)
    {
        if (s[i]>='0' && s[i]<='9')
        {
        while (s[i]>='0' && s[i]<='9')
            {
                ns+=s[i];
                i++;
            }
        ns+='|';
        i--;
        }
        else if (s[i]=='(')
                    st.push('(');
        else if (s[i]==')')
        {
                    while(st.top() != '(' && st.top() != 'N')
                        {
                           char c = st.top();
                           st.pop();
                           ns += c;
                        }
                    if (st.top()=='(') st.pop();
        }
        else {
               while(st.top() != 'N' && prec(s[i])<=prec( st.top() )  )
                  {
                      char c = st.top();
                           st.pop();
                           ns += c;
                  }
                  st.push(s[i]);
             }
    }

    while(st.top() != 'N')
    {
        char c = st.top();
        st.pop();
        ns += c;
    }
    ex=ns;
}

int val(int a,int b,char c)
{
    if (c=='+') return a+b;
    if (c=='-') return a-b;
    if (c=='/') return a/b;
    if (c=='*') return a*b;
}

void eval(string s)
{
     stack<int> ns;
     stack<char> ss;
     bool po=0;
     int l=s.size();
     int o,o1=nmax;
     for (i=0;i<l;i++)
     {
         if (s[i]=='+' || s[i]=='-' || s[i]=='*' || s[i]=='/') {ss.push(s[i]); po=0;}
         else if (s[i]>='0' && s[i]<='9')
         {
             o=0;
             while (s[i]>='0' && s[i]<='9')
                 {o=o*10+s[i]-'0'; i++;} i--;
             if (po)
               while (!ns.empty())
             {
                 o1=ns.top();
                 ns.pop();
                 o=val(o1,o,ss.top());
                 ss.pop();
             }
             ns.push(o);
             po=1;
         }
     }
     fout<<"\n"<<ns.top();
}

int main()
{
    fin>>ex;
    ex=rev(ex);
    itp(ex);
    ex=rev(ex);
    fout<<ex;
    eval(ex);
    return 0;
}