Cod sursa(job #2906824)

Utilizator CReaper1116Shang Cheng Lin CReaper1116 Data 27 mai 2022 16:16:39
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.54 kb
#include <fstream>
//#include <iostream>
using namespace std;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
char v[100000];
int nr[50000];
char op[50000];
int i,n = 0,cnt1 = 0,cnt2 = 0;
int f(){
    int r = 0;
    while(i < n && '0' <= v[i] && v[i] <= '9'){
        r = r*10 + v[i] - '0';
        i++;
    }
    return r;
}
int calc(int a,int b,char ch){
    if(ch == '+')return a + b;
    else if(ch == '-')return a - b;
    else if(ch == '*')return a*b;
    else if(ch == '/')return a/b;
}
void comp(){
    nr[cnt1 - 2] = calc(nr[cnt1 - 2],nr[cnt1 - 1],op[cnt2 - 1]);
    cnt2--;
    cnt1--;
}
int pri[256];
int main()
{
    pri['/'] = 2;
    pri['*'] = 2;
    pri['+'] = 1;
    pri['-'] = 1;
    while(fin>>v[n++]);
    i = 0;
    while(i < n){
        if('0' <= v[i] && v[i] <= '9'){
            nr[cnt1++] = f();
            //cout<<"added"<<nr[cnt1 - 1]<<'\n';
        }else if(v[i] == '('){
            op[cnt2++] = '(';
            i++;
            //cout<<"added"<<'('<<'\n';
        }else if(v[i] == ')'){
            //cout<<"condense\n";
            while(op[cnt2 - 1] != '('){
                comp();
            }
            //cout<<"final:"<<nr[cnt1 - 1]<<'\n';
            cnt2--;
            i++;
        }else if(pri[v[i]]){
            while(cnt2 > 0 && pri[op[cnt2 - 1]] >= pri[v[i]]){
                comp();
            }
            op[cnt2++] = v[i];
            i++;
        }else i++;
    }
    while(cnt1 > 1){
        comp();
    }
    fout<<nr[0];
    return 0;
}