Pagini recente » Cod sursa (job #708553) | Monitorul de evaluare | Istoria paginii runda/dacanuacumatunciniciodata/clasament | Cod sursa (job #2556727) | Cod sursa (job #1459188)
// 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 [1000001] ; // aici se afla forma postfixata
char expresie [1000001] ; // aici se afla forma infixata ( normala )
char stiva [1000001] ; // stiva de operatori si paranteze ( parantezele nu sunt operatori )
int lg_c = -1 ;
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 3 ;
return -1 ;
}
void Citire ()
{
fin.getline ( expresie , 1000001 ) ;
}
bool isoperator ( char c )
{
return ( c == '+' || c == '-' || c == '*' || c == '/' ) ;
}
void ConvertToPostfix ( char expresie [1000001] ) // calculez forma postfixata
{
int vf = 0 , ok , p , i = 0 , lg = strlen ( expresie ) ;
while ( i < lg )
{
ok = 0 ;
while ( expresie [i] >= '0' && expresie [i] <= '9' )
coada [ ++ lg_c ] = expresie [ i ] , ++ i , ok = 1 ;
if ( ok ) coada [ ++ lg_c ] = ',' ;
else
{
p = prioritate ( expresie[i] ) ;
if ( p == 0 ) stiva [ ++ vf ] = expresie [ i ] , ++ i ;
else if ( p == 3 )
{
while ( stiva [vf] != '(' && vf )
coada [ ++ lg_c ] = stiva [ vf ] , -- vf , coada [ ++ lg_c ] = ',' ;
++ i , -- vf ;
}
else
{
while ( vf && p <= prioritate ( stiva [ vf ] ) )
coada [ ++ lg_c ] = stiva [ vf ] , -- vf , coada [ ++ lg_c ] = ',' ;
stiva [ ++ vf ] = expresie [ i ] , ++ i ;
}
}
}
while ( vf )
coada [ ++ lg_c ] = stiva [ vf ] , -- vf , coada [ ++ lg_c ] = ',' ;
}
long stv [1000001] ; // 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 [1000001] ) // Functie ce se aplica pe forma postfixata
{
long b , a , vf = 1 ;
long i = 0 , lg = strlen ( sir ) ;
for ( i = 0 ; i < lg ; )
if ( sir [i] >= '0' && sir [i] <= '9' )
{
stv [ vf ] = atol ( sir + i ) , ++ vf ;
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;
}