Cod sursa(job #1820144)

Utilizator AcuasPopescu Nicolae-Aurelian Acuas Data 1 decembrie 2016 12:16:37
Problema Evaluarea unei expresii Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 2.1 kb
#include <fstream>
#include <cstring>
#include <cstdlib>
using namespace std;
ifstream h("evaluare.in");
ofstream g("evaluare.out");
char p[100005];
int j=0,n; //pozitia curenta din sir;
struct nod{
    int info;
    char type;
    nod* left;
    nod* right;
};
nod* e();
nod* t();
nod* f();
int eval(nod* p){
    int a,b;
    if(p->type==' ')
        return p->info;
    else{
        a=eval(p->left);
        b=eval(p->right);
        switch(p->type){
            case '+': return a+b;
            case '-': return a-b;
            case '*': return a*b;
            case '/': return a/b;
        }
    }
}
void error(int j);
int main(){
    nod* R;
    h.getline(p,100004);
    n=strlen(p);
    R=e();
    if(j<n)
        error(j);
    else
        g<<eval(R)<<' ';
    return 0;
}
nod* e(){
    nod* temp1,*temp2;
    nod* rez;
    temp1=t();
    if(p[j]=='+'){
        j++;
        temp2=e();
        rez=new nod;
        rez->type='+';
        rez->left=temp1;
        rez->right=temp2;
    }
    else if(p[j]=='-'){
        j++;
        temp2=e();
        rez=new nod;
        rez->type='-';
        rez->left=temp1;
        rez->right=temp2;
    }
    else
        rez=temp1;
    return rez;
}
nod* t(){
    nod* temp1,*temp2;
    nod* rez;
    temp1=f();
    if(p[j]=='*'){
        j++;
        temp2=t();
        rez=new nod;
        rez->type='*';
        rez->left=temp1;
        rez->right=temp2;
    }
    else if(p[j]=='/'){
        j++;
        temp2=t();
        rez=new nod;
        rez->type='/';
        rez->left=temp1;
        rez->right=temp2;
    }
    else
        rez=temp1;
    return rez;
}
void error(int j){
    g<<"eroare la caracterul "<<j;
}
nod* f(){
    nod *temp1,*rez;
    if(p[j]=='('){
        j++;
        temp1=e();
        if(p[j]!=')')
            error(j);
        j++;
        rez=temp1;
    }
    else if(isdigit(p[j])){
        int aux=0;
        while(j<=n&&isdigit(p[j])){
            aux=aux*10+p[j]-'0';
            j++;
        }
        rez=new nod;
        rez->type=' ';
        rez->info=aux;
        rez->left=NULL;
        rez->right=NULL;
    }
    else
        error(j);
    return rez;
}