Cod sursa(job #3368372)

Utilizator sandrsSandra Paul sandrs Data 14 octombrie 2026 12:40:05
Problema Eval Scor 20
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.2 kb
#include <fstream>
#include <cmath>
#include <algorithm>
#include <queue>
#include <deque>
#include <string>
#include <unordered_map>
#include <vector>
#include <stack>
#include <deque>
using namespace std;
ifstream cin("eval.in");
ofstream cout("eval.out");
stack<long long> st;
stack<char> op;
long long v[26];
int prioritate(char c)
{
    if(c=='+' || c=='-')
        return 1;
    if(c=='*')
        return 2;
    if(c=='~' || c=='#')
        return 3;
    return 0;
}

void calc()
{
    char c=op.top();
    op.pop();
    long long x=st.top();
    st.pop();
    if(c=='~')
    {
        st.push(-x);
        return;
    }
    if(c=='#')
    {
        st.push(x);
        return;
    }
    long long y=st.top();
    st.pop();
    if(c=='+')
        st.push(y+x);
    if(c=='-')
        st.push(y-x);
    if(c=='*')
        st.push(y*x);
}

int main()
{
    int n;
    string s;
    cin >> n;
    for(int i=0; i<n; i++)
        cin >> v[i];
    cin >> s;
    bool unar=true;
    for(int i=0; i<s.size(); i++)
    {
        char c=s[i];
        if(c>='a' && c<='z')
        {
            st.push(v[c-'a']);
            while(!op.empty() && (op.top()=='~' || op.top()=='#'))
                calc();
            unar=false;
        }
        else if(c=='(' || c=='[')
        {
            op.push(c);
            unar=true;
        }
        else if(c==')' || c==']')
        {
            while(!op.empty() && op.top()!='(' && op.top()!='[')
                calc();
            op.pop();
            if(c==']')
            {
                long long x=st.top();
                st.pop();
                st.push(x*x);
            }
            while(!op.empty() && (op.top()=='~' || op.top()=='#'))
                calc();
            unar=false;
        }
        else
        {
            if(unar)
            {
                if(c=='-')
                    op.push('~');
                if(c=='+')
                    op.push('#');
            }
            else
            {
                while(!op.empty() && prioritate(op.top())>=prioritate(c))
                    calc();
                op.push(c);
                unar=true;
            }
        }
    }

    while(!op.empty())
        calc();
    cout << st.top();

    return 0;
}