Cod sursa(job #2789219)

Utilizator teodorescunicolasteodorescu nicolas alexandru teodorescunicolas Data 27 octombrie 2021 09:58:44
Problema Evaluarea unei expresii Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.2 kb
#include <stdio.h>
#include <cstring>
#define NMAXX 100000

using namespace std;

char s[NMAXX], op[NMAXX], fact[NMAXX];
int n, i, opSize, factSize;

int priority( char ch ) {
    if ( ch == '*' || ch == '/' )
        return 2;
    else if ( ch == '+' || ch == '-' )
        return 1;
    return 0;
}

void pushFact( int a ) {
    fact[factSize++] = a;
}

void pushOp( char ch ) {
    if ( ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '(' || ch == ')' )
        op[opSize++] = ch;
}

int popFact() {
    if ( factSize > 0 )
        return fact[--factSize];
    return 0;
}

char popOp() {
    if ( opSize > 0 )
        return op[--opSize];
    return '\0';
}

char topOp() {
    if ( opSize > 0 )
        return op[opSize - 1];
    return '\0';
}

int calcul( int a, int b, char ch ) {
    int res = 0;

    if ( ch == '*' )
        res = a * b;
    else if ( ch == '/' )
        res = a / b;
    else if ( ch == '+' )
        res = a + b;
    else if ( ch == '-' )
        res = a - b;

    return res;
}

void calculTop() {
    int a, b;

    b = popFact();
    a = popFact();
    pushFact( calcul( a, b, popOp() ) );
}

int element() {
    int nr = 0;

    while ( s[i] >= '0' && s[i] <= '9' ) {
        nr *= 10;
        nr += s[i] - '0';
        i++;
    }

    return nr;
}

int main()
{
    FILE *fin, *fout;

    fin = fopen( "evaluare.in", "r" );
    fout = fopen( "evaluare.out", "w" );

    fgets( s, NMAXX, fin );
    n = strlen( s );

    i = 0;
    while ( i < n ) {
        if ( s[i] >= '0' && s[i] <= '9' )
            pushFact( element() );
        else if ( s[i] == '(' )
            pushOp( s[i++] );
        else if( s[i] == ')' ) {
            while ( topOp() != '(' )
                calculTop();
            popOp();
            i++;
        } else if ( priority( s[i] ) != 0 ) {
            while ( priority( topOp() ) && priority( topOp() ) >= priority( s[i] ) )
                calculTop();
            pushOp( s[i++] );
        } else
            i++;
    }

    while ( opSize > 0 )
        calculTop();

    fprintf( fout, "%d", popFact() );

    fclose( fin );
    fclose( fout );
    return 0;
}