Pagini recente » Cod sursa (job #202243) | Cod sursa (job #2747529) | Cod sursa (job #1083047) | Cod sursa (job #1818799) | Cod sursa (job #3216548)
#include <iostream>
#include <fstream>
#include <cstring>
#include <cctype>
#include <stack>
using namespace std;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
char s[100001];
stack<char> op, polo;
stack <int>r;
int pr(char ch)
{
switch(ch)
{
case '+':
return 1;
case '-':
return 1;
case '*':
return 2;
case '/':
return 2;
case '%':
return 2;
}
return 0;
}
int operatie(int a, int b, char op)
{
switch(op)
{
case '+':
return b + a;
case '-':
return b - a;
case '*':
return b * a;
case '/':
return b / a;
default:
return -1;
}
}
int main()
{
int n, i,a,b;
char ch;
fin.getline(s, 100001);
n = strlen(s);
for(i = 0; i < n; ++i)
{
if(isdigit(s[i]))
{
while(isdigit(s[i]))
{
polo.push(s[i]);
i++;
}
polo.push(' ');
i--;
continue;
}
if(s[i] == '(')
{
op.push(s[i]);
continue;
}
if(s[i] == ')')
{
while(!op.empty() && op.top() != '(')
{
ch = op.top();
polo.push(ch);
op.pop();
}
op.pop();
continue;
}
if(op.empty() || op.top() == '(' || pr(s[i]) > pr(op.top()))
op.push(s[i]);
else
{
while(!op.empty() && pr(s[i]) <= pr(op.top()))
{
ch = op.top();
polo.push(ch);
op.pop();
}
op.push(s[i]);
}
}
while(!op.empty())
{
polo.push(op.top());
op.pop();
}
while(!polo.empty())
{
op.push(polo.top());
polo.pop();
}
int num = 0;
while(!op.empty())
{
if(isdigit(op.top()))
{
num *= 10;
num += op.top() - '0';
op.pop();
}
else if(op.top() == ' ')
{
r.push(num);
num = 0;
op.pop();
}
else
{
a = r.top();
r.pop();
b = r.top();
r.pop();
r.push(operatie(a, b, op.top()));
op.pop();
}
}
fout << r.top();
fin.close();
fout.close();
return 0;
}