Pagini recente » Cod sursa (job #2664101) | Cod sursa (job #1615684) | Cod sursa (job #2505917) | Cod sursa (job #2844333) | Cod sursa (job #792845)
Cod sursa(job #792845)
#include <cstdio>
#include <stack>
#include <cstring>
#define L 100000
using namespace std;
//Precadence
//if(precadence_semn_curent <= precadence_Stack.Top())
//newExp[element_curent++] = semn_curent;
char exp[L];
char newExp[L];
stack<char> Stack;
void citire()
{
scanf("%s\n",&exp);
}
//(1+1)*13+10/2
void InfixToPost(char exp[])
{
int element = 0;
for(int i = 0;i<strlen(exp);i++)
{
char C = exp[i];
if(C == '(')
Stack.push(C);
else
if(C == ')')
{
char top = Stack.top();
while(top != '(')
{
newExp[element++] = top;
Stack.pop();
top = Stack.top();
}
Stack.pop();
}
else
if(C == '+' || C == '-')
{
if(Stack.empty() == true || Stack.top() == '(')
{Stack.push(C);
newExp[element++] = '.';
}
else
{
newExp[element++] = Stack.top();
Stack.pop();
Stack.push(C);
newExp[element++] = '.';
}
}
else
if(C == '*' || C == '/')
{
if(Stack.empty() == true)
{Stack.push(C);
newExp[element++] = '.';
}
else
{
while(Stack.top() == '*' || Stack.top() == '/')
{
newExp[element++] = Stack.top();
Stack.pop();
}
Stack.push(C);
newExp[element++] = '.';
}
}
else
{
newExp[element++] = C;
}
}
while(Stack.empty() != true)
{
newExp[element++]=Stack.top();
Stack.pop();
}
}
int termen(int &i)
{
int x =0;
while(newExp[i] != '.' && newExp[i] != '+' && newExp[i] != '-' && newExp[i] != '*' && newExp[i] != '/')
{
x = x*10 + newExp[i]-'0';
i++;
}
i--;
return x;
}
int evalExp(char newExp[])
{
stack<int> evalStack;
for(int i = 0;i<strlen(newExp);i++)
{
if(newExp[i] == '.')
i++;
if(newExp[i] == '+' || newExp[i] == '*' || newExp[i] == '/' || newExp[i] =='-')
{
int x,y;
x = evalStack.top();
evalStack.pop();
y = evalStack.top();
evalStack.pop();
if(newExp[i] == '+')
evalStack.push(x+y);
else
if(newExp[i] == '-')
evalStack.push(y-x);
else
if(newExp[i] == '*')
evalStack.push(x*y);
else
evalStack.push(y/x);
}
else
{
int x = termen(i);
evalStack.push(x);
}
}
return evalStack.top();
}
int main()
{
freopen("evaluare.in","r",stdin);
freopen("evaluare.out","w",stdout);
citire();
InfixToPost(exp);
printf("%d\n",evalExp(newExp));
return 0;
}