Cod sursa(job #2220636)

Utilizator AndreiOffCovaci Andrei-Ion AndreiOff Data 12 iulie 2018 12:03:32
Problema Evaluarea unei expresii Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.03 kb
#include <iostream>
#include <fstream>
#include <string.h>
#include <string>
#include <vector>

using namespace std;

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

char s[100005];

int x, n;

vector<char> st;

vector<int> rez;

int calculate(char ch){

    int x = 0, y = 0, z = 1;

    x = rez.back();
    rez.pop_back();
    y = rez.back();
    rez.pop_back();

    switch(ch){

    case '^':
        while(x){

            if(x % 2) z *= y;
            else {

                y *= y;
                x /= 2;

            }

        }

        return z;

    case '*':
        return y*x;

    case '/':
        return y/x;

    case '+':
        return y + x;

    case '-':
        return y - x;

    default : break;

    }

    return 0;

}

int grade(char ch){

    switch(ch){

        case '^': return 4;
        case '/': return 3;
        case '*': return 3;
        case '-': return 2;
        case '+': return 2;
        default: break;

    }

    return 0;

}

int main()
{

f.getline(s, 100005);

n = strlen(s);

for(int i = 0; i < n; i++){

    while(s[i] >= '0' && s[i] <= '9' && i < n){

        x = x*10 + (s[i] - '0');
        i++;

    }

    if(x){

        i--;

        rez.push_back(x);

        x = 0;

    }else{

        while(!st.empty() && st.back() != '(' && (grade(st.back()) > grade(s[i]) || (grade(st.back()) == grade(s[i]) && st.back() != '^'))){

                rez.push_back(calculate(st.back()));
                st.pop_back();

              }


        if(s[i] == '(')
            st.push_back(s[i]);

        else if(s[i] == ')'){

            while(st.back() != '('){

                    rez.push_back(calculate(st.back()));
                    st.pop_back();

                  }

            st.pop_back();

        }else st.push_back(s[i]);

    }


}

while(!st.empty()){

    rez.push_back(calculate(st.back()));
    st.pop_back();

}

g<<rez.back();

    return 0;
}