Pagini recente » Cod sursa (job #3164467) | Cod sursa (job #2968703) | Cod sursa (job #1551035) | Cod sursa (job #1680231) | Cod sursa (job #2008732)
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
#include <sstream>
using namespace std;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
struct elemS
{
bool typ;// 0 - nr, 1 - operator;
char op;
int nr;
};
string expr;
vector< elemS > postfix;
stack< char > st;
int priority( char op )
{
if( op == '+' || op == '-' )
return 1;
else if( op == '*' || op == '/' )
return 2;
else
return 0;
}
int main()
{
fin >> expr;
int i = 0;
while( i < expr.size() )
{
//cerr << i << "\n";
if( expr[i] >= 48 && expr[i] <= 57 )
{
// number
string nrs;
while( expr[i] >= 48 && expr[i] <= 57 )
{
nrs.push_back( expr[i] );
++i;
}
istringstream nrss( nrs );
elemS ne;
ne.typ = 0;
nrss >> ne.nr;
postfix.push_back( ne );
}
else if( expr[i] == '(' )
{
st.push( expr[i] );
++i;
}
else if( expr[i] == ')' )
{
while( st.size() && st.top() != '(' )
{
elemS ne;
ne.typ = 1;
ne.op = st.top();
postfix.push_back( ne );
st.pop();
}
if( st.size() )
st.pop();
++i;
}
else
{
// operator
if( !st.size() )
st.push( expr[i] );
else
{
while( st.size() && priority( st.top() ) >= priority( expr[i] ) )
{
elemS ne;
ne.typ = 1;
ne.op = st.top();
postfix.push_back( ne );
st.pop();
}
st.push( expr[i] );
}
++i;
}
}
while( st.size() )
{
if( st.top() != '(' )
{
elemS ne;
ne.typ = 1;
ne.op = st.top();
postfix.push_back( ne );
}
st.pop();
}
/*/
for( int i = 0; i < postfix.size(); ++i )
{
if( postfix[i].typ == 0 )
cout << postfix[i].nr << " " ;
else
cout << postfix[i].op << " ";
}
cout << "\n";
//*/
stack< int > nrst;
for( int i = 0; i < postfix.size(); ++i )
{
if( postfix[i].typ == 0 )
nrst.push( postfix[i].nr );
else
{
int nr1 = nrst.top(); nrst.pop();
int nr2 = nrst.top(); nrst.pop();
// cout << nr1 << " " << postfix[i].op << " " << nr2 << "\n";
int res;
if( postfix[i].op == '+' )
res = nr2 + nr1;
if( postfix[i].op == '-' )
res = nr2 - nr1;
if( postfix[i].op == '*' )
res = nr2 * nr1;
if( postfix[i].op == '/' )
res = nr2 / nr1;
nrst.push( res );
}
}
//cout << "\n";
fout << nrst.top() << "\n";
return 0;
}