Pagini recente » Borderou de evaluare (job #1383246) | Borderou de evaluare (job #2971372) | Borderou de evaluare (job #2681083) | Borderou de evaluare (job #361457) | Cod sursa (job #362412)
Cod sursa(job #362412)
#include <stack>
#include <vector>
#include <string>
#include <fstream>
#include <algorithm>
#define pb push_back
/*
*
*/
using namespace std;
typedef string::iterator iter;
ifstream in;
ofstream out;
int constant[30];
string Functions[30];
inline int priority( char x )
{
if( '(' == x )
return 0;
if( '+' == x || '-' == x )
return 1;
if( '*' == x || '/' == x )
return 2;
if( ')' == x )
return 3;
return -1;
}
string transform( iter it, iter iend )
{int p;
stack<char> s;
string t;
while( it < iend )
{
if( *it >= 'a' && *it <= 'b' )
{
t.pb(*it); ++it;
continue;
}
if( *it >= '0' && *it <= '9' )
{
while( it < iend && *it >= '0' && *it <= '9' )
t.pb(*it), ++it;
t.pb(' ');
continue;
}
if( '(' == *it )
{
s.push(*it); ++it;
continue;
}
if( ')' == *it )
{++it;
while( !s.empty() && '(' != s.top() )
t.pb(s.top()), s.pop();
s.pop();
continue;
}
p=priority(*it);
while( !s.empty() && p <= priority(s.top()) )
t.pb(s.top()),s.pop();
s.push(*it); ++it;
}
while( !s.empty() )
t.pb(s.top()),s.pop();
return t;
}
inline int getnumber( iter& it, iter iend )
{int number=0;
while( it < iend && *it >= '0' && *it <= '9' )
number=number*10+*it-'0', ++it;
return number;
}
int evaluate( iter it, iter iend, vector<int>* arguments )
{int number, a, b;
stack<int> v;
while( it < iend )
{
if( *it >= 'a' && *it <= 'z' )
{
v.push( arguments->at(*it-'a') ); ++it;
continue;
}
if( *it >= '0' && *it <= '9' )
{
v.push( getnumber( it, iend ) );
++it;
continue;
}
b=v.top(); v.pop();
a=v.top(); v.pop();
switch(*it)
{
case '+' : v.push(a+b); break;
case '-' : v.push(a-b); break;
case '*' : v.push(a*b); break;
case '/' : v.push(a/b); break;
}
++it;
}
return v.top();
}
int main()
{string expresion;
in.open("evaluare.in");
getline( in, expresion );
expresion=transform( expresion.begin(), expresion.end() );
out.open("evaluare.out");
out<<evaluate( expresion.begin(), expresion.end(), NULL );
return 0;
}