Cod sursa(job #1758102)

Utilizator alexrusRus Alexandru alexrus Data 16 septembrie 2016 16:04:55
Problema Evaluarea unei expresii Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.02 kb
#include<iostream>
#include<fstream>
#include<string.h>
using namespace std;
char s[100001];
int lg=-1;
typedef struct node
{
    char inf;
    int val;
    node *left,*right;
} node;
int numar(char *s, int &i)
{
    int n=0;
    while(s[i]>='0' && s[i]<='9' && i<strlen(s))
        n=n*10+s[i++]-'0';
    i--;
    return n;
}
node *arbore(int &i);
node *factor(int &i)
{
    node *p;
    if(s[i]=='(')
      p=arbore(++i);
    else
    {

        p=new node;
        p->val=numar(s,i);
        p->left=p->right=NULL;
    }
    i++;
    return p;
}
node *termen(int &i)
{
    node*p,*r;
    r=factor(i);
    if(s[i]==')' || (s[i]!='*' && s[i]!='/') || i>=strlen(s))
        return r;
    p=new node;
    p->left=r;
    p->inf=s[i++];
    p->right=termen(i);
    return p;
}
node *arbore(int &i)
{
    node *p,*r;
    while(i<strlen(s) && s[i]!=')')
        if(strchr("+-*/",s[i]))
        {
            p=new node;
            p->left=r;
            p->inf=s[i++];
            p->right=termen(i);
        }
        else
        {
            r=termen(i);
            if(i>=strlen(s) || s[i]==')')
            {return r;}
            p=new node;
            p->left=r;
            p->inf=s[i++];
            p->right=termen(i);
        }
    return p;
}
int operatie(int a,int b,char op)
{
    switch (op)
    {   case '+':return a+b;break;
        case '-':return a-b;break;
        case '*':return a*b;break;
        case '/':return a/b;break;
    }
}
void calc(node *p)
{
    if(p)
    {
        if(strchr("+-/*",p->left->inf))
            calc(p->left);

        if(strchr("+-/*",p->right->inf))
            calc(p->right);
            p->val=operatie(p->left->val,p->right->val,p->inf);
    }
}
int main()
{
    node *p=NULL;
    int i=0;
    ifstream f("evaluare.in");
    ofstream g("evaluare.out");
    f>>s[++lg];
    while(!f.eof())
        f>>s[++lg];
        p=arbore(i);
    calc(p);
    g<<p->val;
    f.close();
    g.close();
    return 0;
}