Pagini recente » Cod sursa (job #2038857) | Cod sursa (job #2968601) | Cod sursa (job #2778463) | Cod sursa (job #979214) | Cod sursa (job #1419400)
#include <iostream>
#include <cstdio>
#include <cstring>
#include <stack>
#include <cstdlib>
using namespace std;
const int mx = 100005 ;
int n,p ;
char s[mx] ;
char polo[mx][12] ;
int val( char c )
{
if ( c == '(' || c == ')' )
return 0 ;
if ( c == '+' || c == '-' )
return 1 ;
return 2 ;
}
void poloneza()
{
stack <char> S;
int i = 0 ;
while ( i < n )
if ( isdigit(s[i]) )
{
int t = 0 ;
while ( isdigit(s[i]) )
polo[p][t++] = s[i++] ;
p ++ ;
}
else if ( s[i] == '(' )
S.push(s[i++]) ;
else
{
while ( not S.empty() && val(s[i]) <= val(S.top()) )
{
if ( S.top() != '(' )
polo[p++][0] = S.top() ;
S.pop() ;
}
if ( s[i] != ')' )
S.push(s[i]) ;
i ++ ;
}
while ( not S.empty() )
{
if ( S.top() != '(' )
polo[p++][0] = S.top() ;
S.pop() ;
}
}
int rez( int a , int b , char s )
{
if ( s == '+' )
return a + b ;
if ( s == '-' )
return a - b ;
if ( s == '*' )
return a * b ;
return a / b ;
}
void evaluare()
{
stack <int> S;
for ( int i = 0 ; i < p ; i ++ )
if ( isdigit(polo[i][0]) )
S.push( atoi( polo[i] ) ) ;
else
{
int a = S.top() ;
S.pop() ;
int b = S.top() ;
S.pop() ;
S.push(rez(b , a , polo[i][0])) ;
}
printf( "%d\n" , S.top() ) ;
}
int main()
{
freopen( "evaluare.in" , "r" , stdin ) ;
freopen( "evaluare.out" , "w" , stdout ) ;
scanf( "%s" , s ) ;
n = strlen(s) ;
poloneza() ;
evaluare() ;
return 0;
}