Pagini recente » Cod sursa (job #3157448) | Cod sursa (job #1633431) | Cod sursa (job #806814) | Cod sursa (job #1503650) | Cod sursa (job #2851083)
#include <bits/stdc++.h>
#define ll long long
using namespace std;
ifstream in("evaluare.in");
ofstream out("evaluare.out");
int priority(char c)
{
switch(c)
{
default:
return -1;
case '*':
case '/':
return 2;
case '+':
case '-':
return 1;
}
}
string postfix(string e)
{
string rez="";
stack <char> stiva;
for(int i=0; i<e.size(); i++)
{
if(e[i]>='0' && e[i]<='9')
{
rez+=e[i];
if(!(e[i+1]>='0' && e[i+1]<='9')) rez+='|';
}
else
{
switch(e[i])
{
case '(':
stiva.push(e[i]);
break;
case ')':
{
while(stiva.top()!='(')
{
rez+=stiva.top();
stiva.pop();
}
stiva.pop();
break;
}
default:
{
if(!stiva.empty())
while(priority(e[i])<=priority(stiva.top()))
{
rez+=stiva.top();
stiva.pop();
if(stiva.empty()) break;
}
stiva.push(e[i]);
break;
}
}
}
}
while(!stiva.empty())
{
rez+=stiva.top();
stiva.pop();
}
return rez;
}
ll ToNum(string s)
{
ll x=0;
for(int i=0;i<s.size();i++)
x=x*10+int(s[i]-48);
return x;
}
ll calcul(ll a,ll b, char op)
{
switch(op)
{
default: return -1;
case '+': return a+b;
case '-': return a-b;
case '*': return a*b;
case '/': return a/b;
}
}
int main()
{
string s="",e="";
in>>s;
e=postfix(s);
//cout<<e;
stack <ll> stiva;
for(int i=0;i<e.size();i++)
{
if(e[i]>='0' && e[i]<='9')
{
string nr="";
for(;e[i]!='|';i++)
nr+=e[i];
stiva.push(ToNum(nr));
//cout<<nr<<'\n';
}
else
{
ll a,b;
a=stiva.top();
stiva.pop();
b=stiva.top();
stiva.pop();
stiva.push(calcul(b,a,e[i]));
}
}
out<<stiva.top();
return 0;
}