Pagini recente » Istoria paginii runda/78687jhjhjh | Cod sursa (job #1248538) | Cod sursa (job #2587224) | Istoria paginii runda/simulare-cartita-15a/clasament | Cod sursa (job #1459172)
// Se aduce expresia la forma poloneza ( postfixata )
// Se evalueaza noua expresie
#include <iostream>
#include <fstream>
#include <cstring>
#include <cstdlib>
using namespace std;
ifstream fin ("evaluare.in") ;
ofstream fout ("evaluare.out") ;
char coada [100001] ; // aici se afla forma postfixata
int lg_c = -1 ;
char expresie [100001] ; // aici se afla forma infixata ( normala )
int prioritate ( char op )
{
if ( op == '(' ) return 0 ;
if ( op == '+' ) return 1 ;
if ( op == '-' ) return 1 ;
if ( op == '/' ) return 2 ;
if ( op == '*' ) return 2 ;
if ( op == ')' ) return 4 ;
return -1 ;
}
char stiva [100001] ; // stiva de operatori si paranteze ( parantezele nu sunt operatori )
void Citire ()
{
char c ;
int l = 0 ;
while ( fin >> c )
expresie [l] = c , ++ l ;
expresie [l] = 0 ;
}
bool isoperator ( char c )
{
return ( strchr ( "+-/*" , c ) != 0 ) ;
}
void ConvertToPostfix ( char expresie [100001] ) // calculez forma postfixata
{
unsigned int i = 0 ;
int vf = 0 , ok , p ;
while ( i < strlen ( expresie ) )
{
ok = 0 ;
while ( expresie[i] >= '0' && expresie [i] <= '9' )
coada [ ++ lg_c ] = expresie [ i ++ ] , ok = 1 ;
if ( ok ) coada [ ++ lg_c ] = ',' ;
else
{
p = prioritate ( expresie[i] ) ;
if ( p == 0 ) stiva [ ++ vf ] = expresie [ i ++ ] ;
else if ( p == 4 )
{
while ( stiva [vf] != '(' && vf )
coada [ ++ lg_c ] = stiva [ vf -- ] , coada [ ++ lg_c ] = ',' ;
++ i ; -- vf ;
}
else
{
while ( vf && p <= prioritate ( stiva [ vf ] ) )
coada [ ++ lg_c ] = stiva [ vf -- ] , coada [ ++ lg_c ] = ',' ;
stiva [ ++ vf ] = expresie [ i ++ ] ;
}
}
}
while ( vf ) coada [ ++ lg_c ] = stiva [ vf -- ] , coada [ ++ lg_c ] = ',' ;
}
long stv [100001] ; // aici pun operanzii
// Cand un operator este intalnit scot de pe stiva ultimii 2 operanzi , aplic operatorul intre ei si rezultatul este pus in varful stivei
long EvaluareExpresie ( char sir [100001] ) // Functie ce se aplica pe forma postfixata
{
long b , a , vf = 1 ;
unsigned long i ;
for ( i = 0 ; i < strlen ( sir ) ; )
if ( sir [i] >= '0' && sir [i] <= '9' )
{
stv [ vf++ ] = atol ( sir + i ) ;
while ( sir [i] >= '0' && sir [i]<='9') ++i ;
++ i ; // scap de comma
}
else
{
if ( isoperator( sir [i] ) == true )
{
b = stv [ --vf ] ; a = stv [ -- vf ] ;
switch ( sir[i] )
{
case '+' : stv [ vf ] = a + b ; break ;
case '-' : stv [ vf ] = a - b ; break ;
case '*' : stv [ vf ] = a * b ; break ;
case '/' : stv [ vf ] = a / b ; break ;
}
++ vf;
}
i += 2 ; // sar peste operator si peste comma
}
return stv [1];
}
int main()
{
Citire () ;
ConvertToPostfix ( expresie ) ;
fout << EvaluareExpresie ( coada ) ;
return 0;
}