Pagini recente » Cod sursa (job #930757) | Cod sursa (job #1524494) | Cod sursa (job #725624) | Cod sursa (job #1817210) | Cod sursa (job #2169931)
#include <fstream>
#include <cstring>
#include <stack>
using namespace std;
ifstream fi("evaluare.in");
ofstream fo("evaluare.out");
char a[100001];
char b[100001];
char res[500005];
int k=0;
bool operand(char exp)
{
if(exp>='0' and exp<='9')
return 1;
return 0;
}
bool operator_(char exp)
{
if(exp=='+' or exp=='-' or exp=='*' or exp=='/')
return 1;
return 0;
}
int priority(char a)
{
if(a=='+' or a=='-')
return 1;
if(a=='*' or a=='/')
return 2;
return 0;
}
void afisare(stack <char> s2)
{
while(!s2.empty())
{
fo<<s2.top();
s2.pop();
}
fo<<endl;
}
void infix_postfix(char exp[100001])
{
stack <char> s;
for(int i=0;i<strlen(exp);i++)
{
if(operand(exp[i]))
{
while(exp[i]>='0' and exp[i]<='9' and i<strlen(exp))
{
res[k++]=exp[i];
i++;
}
res[k++]=' ';
i--;
}
else if(operator_(exp[i]))
{
while(!s.empty() and s.top()!='(' and priority(s.top())>=priority(exp[i]))
{
res[k++]=s.top();
s.pop();
}
s.push(exp[i]);
}
else if(exp[i]=='(')
s.push(exp[i]);
else if(exp[i]==')')
{
while(s.top()!='(')
{
res[k++]=s.top();
s.pop();
}
s.pop();
}
}
while(!s.empty())
{
res[k++]=s.top();
s.pop();
}
}
void evaluation()
{
stack <int> s;
int op;
for(int i=0;i<k;i++)
{
op=0;
if(operand(res[i]))
{
while(operand(res[i]) and i<k)
{
op=op*10+(res[i]-'0');
i++;
}
i--;
s.push(op);
}
else if(operator_(res[i]))
{
int b=s.top();
s.pop();
int a=s.top();
s.pop();
// if(!s.empty())
// {
// a=s.top();
// s.pop();
// }
// else
// if(res[i]=='+' or res[i]=='-')
// a=0;
// else
// a=1;
if(res[i]=='+')
s.push(a+b);
if(res[i]=='-')
s.push(a-b);
if(res[i]=='*')
s.push(a*b);
if(res[i]=='/')
s.push(a/b);
}
}
fo<<s.top();
}
int main()
{
fi.getline(a,100001);
// stack s2<int> ;
// for(int i=0;i<strlen(a);i++)
// {
// if(s[i]=='(')
// {
// s2.push(i);
// }
// if(s[i]==')')
// {
// int start=s2.top();
// s2.pop();
//
// }
// }
infix_postfix(a);
evaluation();
return 0;
}