Cod sursa(job #2061639)
Utilizator | Data | 9 noiembrie 2017 16:14:58 | |
---|---|---|---|
Problema | Evaluarea unei expresii | Scor | 80 |
Compilator | cpp | Status | done |
Runda | Arhiva educationala | Marime | 4.71 kb |
#include <cstdio>
#include <cstring>
#include <vector>
#include <cctype>
#include <stack>
using namespace std;
stack<int> polo;
stack<char> op;
char s[10001];
inline int prioritate(char ch)
{
switch(ch)
{
case '*':
case '/':
case '%': return 2;
case '+':
case '-': return 1;
default : return 0;
}
}
int main()
{
freopen("evaluare.in","r",stdin);
freopen("evaluare.out","w",stdout);
int n,i,a;
char x;
gets(s);
n=strlen(s);
for(i=0;i<n;i++)
{
if(isdigit(s[i]))
{
a=0;
while(i<n&&isdigit(s[i]))
{
a=a*10;
a+=(s[i]-'0');
i++;
}
polo.push(a);
i--;
continue;
}
if(s[i]=='(')
{
op.push(s[i]);
continue;
}
if(s[i]==')')
{
while(!op.empty()&&op.top()!='(')
{
//polo.push_back(op.top());
x=op.top();
switch(x)
{
case '*':{
a=polo.top();
polo.pop();
polo.top()*=a;
break;
}
case '/':{
a=polo.top();
polo.pop();
polo.top()/=a;
break;
}
case '%':{
a=polo.top();
polo.pop();
polo.top()%=a;
break;
}
case '+':{
a=polo.top();
polo.pop();
polo.top()+=a;
break;
}
case '-':{
a=polo.top();
polo.pop();
polo.top()-=a;
break;
}
default : break;
}
op.pop();
}
op.pop();
continue;
}
if(op.empty()||prioritate(op.top())<prioritate(s[i]))
op.push(s[i]);
else
{
while(!op.empty()&&prioritate(op.top())>=prioritate(s[i]))
{
//polo.push(op.top());
x=op.top();
switch(x)
{
case '*':{
a=polo.top();
polo.pop();
polo.top()*=a;
break;
}
case '/':{
a=polo.top();
polo.pop();
polo.top()/=a;
break;
}
case '%':{
a=polo.top();
polo.pop();
polo.top()%=a;
break;
}
case '+':{
a=polo.top();
polo.pop();
polo.top()+=a;
break;
}
case '-':{
a=polo.top();
polo.pop();
polo.top()-=a;
break;
}
default : break;
}
op.pop();
}
op.push(s[i]);
}
}
while(!op.empty())
{
//polo.push(op.top());
x=op.top();
switch(x)
{
case '*':{
a=polo.top();
polo.pop();
polo.top()*=a;
break;
}
case '/':{
a=polo.top();
polo.pop();
polo.top()/=a;
break;
}
case '%':{
a=polo.top();
polo.pop();
polo.top()%=a;
break;
}
case '+':{
a=polo.top();
polo.pop();
polo.top()+=a;
break;
}
case '-':{
a=polo.top();
polo.pop();
polo.top()-=a;
break;
}
default : break;
}
op.pop();
}
printf("%d",polo.top());
return 0;
}