Pagini recente » Cod sursa (job #1471317) | Cod sursa (job #1306852) | Cod sursa (job #2816945) | Cod sursa (job #1990807) | Cod sursa (job #1349930)
#include <cstdio>
#include <stack>
#include <vector>
#include <cstring>
using namespace std;
const int nmax = 100000;
struct str
{
bool op;
int val;
str() { op = false; val = 0; }
str (int x, int y) { op = x; val = y; }
};
char a[nmax+5];
stack <int> op;
vector <str> polo;
int priority[300];
inline int conv(char x)
{
if(x == '+')return 10;
if(x == '-')return 11;
if(x == '*')return 12;
if(x == '/')return 13;
if(x == '(')return 14;
if(x == ')')return 15;
if('0' <= x && x<='9')return x-'0';
}
inline int calc(int a, int b, int op)
{
if(op == 10)return a+b;
if(op == 11)return a-b;
if(op == 12)return a*b;
if(op == 13)return a/b;
}
int main()
{
freopen("evaluare.in", "r", stdin);
freopen("evaluare.out", "w", stdout);
priority[10]=priority[11]=1;
priority[12]=priority[13]=2;
int n;
gets(a);
n=strlen(a);
for(int i=0; i<n; i++)
{
a[i] = conv(a[i]);
if(a[i] == 14)// (
op.push(14);
else if(a[i] == 15)// )
{
while(op.top()!=14)
{
polo.push_back(str(1, op.top()));
op.pop();
}
op.pop();
}
else if(10 <= a[i] && a[i]<= 13)//is operator
{
while(!op.empty() && priority[(int)a[i]]<=priority[(int)op.top()])
{
polo.push_back(str(1, op.top()));
op.pop();
}
op.push(a[i]);
}
else // is digit
{
int nr = 0;
while(i<n && 0 <= a[i] && a[i] < 10)
{
nr = nr*10 + a[i];
i++;
a[i] = conv(a[i]);
}
i--;
polo.push_back(str(0, nr));
}
}
while(!op.empty())
{
polo.push_back(str(1, op.top()));
op.pop();
}
for(int i=0; i<polo.size(); i++)
{
if(polo[i].op == true)
{
int ans = calc(polo[i-2].val, polo[i-1].val, polo[i].val);
polo.erase(polo.begin()+i-2, polo.begin()+i);
i-=2;
polo[i] = str(0, ans);
}
}
printf("%d\n", polo[0].val);
return 0;
}