Pagini recente » Cod sursa (job #1197132) | Cod sursa (job #957163) | Cod sursa (job #861473) | Cod sursa (job #324459) | Cod sursa (job #2515574)
#include <stack>
#include <cctype>
#include <cstdio>
#include <cstring>
using namespace std;
const int BUFF_SIZE = 65536 ;
char buffer [ BUFF_SIZE + 5 ] ;
int poz = BUFF_SIZE ;
char operators [] = "+-/*" ;
inline char getch ( FILE * f )
{
if ( poz == BUFF_SIZE )
fread ( buffer + 1 , 1 , BUFF_SIZE , f ) , poz = 0 ;
return buffer [ ++ poz ] ;
}
inline int app_op ( int a , int b , char ch )
{
if ( ch == '+' ) return a + b ;
else if ( ch == '-' ) return b - a ;
else if ( ch == '*' ) return a * b ;
else if ( ch == '/' ) return b / a ;
}
inline int priority ( char a )
{
if ( a == '(' ) return - 1 ;
if ( a == '*' || a == '/' ) return 2 ;
if ( a == '+' || a == '-' ) return 1 ;
return 0 ;
}
int evaluate ( FILE * f )
{
char ch ;
int nr = 0 , val1 , val2 ;
stack < int > num ;
stack < char > ops ;
while ( 1 )
{
ch = getch ( f ) ;
here : ;
if ( isdigit ( ch ) )
nr = nr * 10 + ( int ) ( ch - '0' ) ;
else
if ( strchr ( operators , ch ) != NULL )
{
if ( nr ) num.push ( nr ) , nr = 0 ;
char ch1 = ch ;
while ( 1 )
{
ch = getch ( f ) ;
if ( ! isdigit ( ch ) )
break ;
nr = nr * 10 + ( int ) ( ch - '0' ) ;
}
while ( ! ops.empty () && priority ( ch1 ) < priority ( ops.top () ) )
{
val1 = num.top () ; num.pop () ;
val2 = num.top () ; num.pop () ;
num.push ( app_op ( val1 , val2 , ops.top () ) ) ;
ops.pop () ;
}
num.push ( nr ) ; nr = 0 ;
ops.push ( ch1 ) ;
goto here ;
}
else
if ( ch == '(' )
ops.push ( ch ) ;
else
if ( ch == ')' )
{
while ( ops.top () != '(' )
{
val1 = num.top () ; num.pop () ;
val2 = num.top () ; num.pop () ;
num.push ( app_op ( val1 , val2 , ops.top () ) ) ;
ops.pop () ;
}
ops.pop () ;
}
else
goto ending ;
}
ending : ;
while ( ! ops.empty () )
{
val1 = num.top () ; num.pop () ;
val2 = num.top () ; num.pop () ;
num.push ( app_op ( val1 , val2 , ops.top () ) ) ;
ops.pop () ;
}
return num.top () ;
}
int main()
{
FILE * f ;
f = fopen ( "evaluare.in" , "r" ) ;
freopen ( "evaluare.out" , "w" , stdout ) ;
printf ( "%d" , evaluate ( f ) ) ;
return 0;
}