Pagini recente » Cod sursa (job #961611) | Cod sursa (job #2059586) | Cod sursa (job #2401669) | Cod sursa (job #229437) | Cod sursa (job #2946858)
#include <fstream>
#include<vector>
#include <algorithm>
#import <cmath>
#import <cassert>
#import <queue>
#import <map>
#import <stack>
using namespace std;
namespace EXP
{
int cod(char ch)
{
if(ch=='/')return 2;
if(ch=='*')return 2;
if(ch=='-' || ch=='+')return 1;
return 0;
}
int aplic(int a,int b,char c)
{
if(c=='+')return a+b;
if(c=='-')return a-b;
if(c=='/')return a/b;
return a*b;
}
stack<int>val;
stack<char>op;
void calc()
{
int v2=val.top();
val.pop();
int v1=val.top();
val.pop();
char o=op.top();
op.pop();
val.push(aplic(v1,v2,o));
}
int solve(string s)
{
s="("+s+")";
int n=(int)s.size();
for(int i=0; i<n; i++)
{
if(s[i]==' ')continue;
if(s[i]=='(')
{
op.push(s[i]);
continue;
}
else if(s[i]==')')
{
while(op.top()!='(')calc();
op.pop();
}
else if(isdigit(s[i]))
{
int x=0;
while(isdigit(s[i]))
{
x=x*10+(s[i])-'0';
i++;
}
val.push(x);
i--;
}
else
{
while(cod(s[i])<=cod(op.top()))calc();
op.push(s[i]);
}
}
return val.top();
}
}
main()
{
ifstream cin("evaluare.in");
ofstream cout("evaluare.out");
string s;
cin>>s;
cout<<EXP::solve(s);
}