Cod sursa(job #752146)
#include <string>
#include <fstream>
#include <cstdlib>
using namespace std;
struct nod {
int x;
char c;
nod *left, *right;
nod() : x(-(1<<30)), c(0), left(NULL), right(NULL) {}
nod(int _x, nod *_left, nod *_right) : x(_x), left(_left), right(_right) {}
nod(char _c, nod *_left, nod *_right) : c(_c), left(_left), right(_right) {}
};
typedef nod *pnod;
string exp;
string::const_iterator it, iend;
const string op[]={ "+-", "*/", "^"};
inline int eval(int a, int b, char op)
{
switch(op)
{
case '+' : return a+b;
case '-' : return a-b;
case '*' : return a*b;
case '/' : return a/b;
}
return -(1<<30);
}
pnod createTree(int level)
{
pnod x=new nod();
if(2 == level)
{
if('(' == *it)
{
++it;
x=createTree(0);
++it;
}
else for(x->x=0; it < iend && *it >= '0' && *it <= '9'; ++it)
x->x=x->x*10+*it-'0';
}
else for(x=createTree(level+1); it < iend && string::npos != op[level].find(*it); )
{
pnod y=new nod();
y->left=x;
y->c=*it; ++it;
y->right=createTree(level+1);
x=y;
}
return x;
}
int eval(pnod p)
{
if(NULL == p->left && NULL == p->right)
return p->x;
return eval(eval(p->left), eval(p->right), p->c);
}
int main()
{
pnod root;
ifstream in("evaluare.in");
ofstream out("evaluare.out");
getline(in, exp);
it=exp.begin(), iend=exp.end();
root=createTree(0);
out<<eval(root)<<"\n";
return EXIT_SUCCESS;
}