Cod sursa(job #952659)

Utilizator deea101Andreea deea101 Data 23 mai 2013 19:31:46
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.09 kb
#include <fstream>
#include <vector>
using namespace std;
ifstream f("evaluare.in");
ofstream g("evaluare.out");
vector <char> op;
vector <int> stiva;
int zise=0,numere[100001],nrs=0;
char in[100001],out[100001];
int pr( char c )
{
    if(c=='+' || c=='-') return 1;
    if(c=='*' || c=='/') return 2;
    if(c=='(') return -1;
}

void getdigit( char *&p )
{
    int nr=0;
    while (0<=(*p-'0') && (*p-'0')<=9)
    {
        nr=nr*10+((*p)-'0');
        p++;
    }
    out[++zise]='~';
    numere[++nrs]=nr;
}

int main()
{
    f>>in;
    char *p;
    p=in;
    while((*p)!='\0')
    {
        if(0<=(*p-'0') && (*p-'0')<=9) getdigit(p);
        else
        {
            if((*p)=='(') {op.push_back(*p); p++; continue;}
            if((*p)==')')
            {
                while(op.back()!='(')
                {
                    out[++zise]=op.back();
                    op.pop_back();
                }
                op.pop_back();
                p++; continue;
            }

            if(op.empty())
                op.push_back(*p);
            else
            {
                while(pr(op.back())>=pr(*p))
                {
                    out[++zise]=op.back();
                    op.pop_back();
                    if(op.empty()) break;
                }
                op.push_back(*p);
            }
            p++;
        }
    }
    while(!op.empty())
    {
        out[++zise]=op.back();
        op.pop_back();
    }

    /*for(int i=1, k=1 ;i<=zise ; i++)
    {
        if(out[i]=='~') g<<numere[k++];
        else g<<out[i];
    }*/

    int i=1, k=1; int a,b;
    while(i<=zise)
    {
        if(out[i]=='~') stiva.push_back(numere[k++]);
        else
        {
            b=stiva.back(); stiva.pop_back();
            a=stiva.back(); stiva.pop_back();
            if(out[i]=='+') stiva.push_back(a+b);
            if(out[i]=='-') stiva.push_back(a-b);
            if(out[i]=='*') stiva.push_back(a*b);
            if(out[i]=='/') stiva.push_back(a/b);
        }
        i++;
    }
    g<<stiva.front();

}