#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int *stackbase;
int *stack;
int stack_size;

void stackerr(char* str)
{
    printf("%s\n", str);
    exit(999);
}

void init_stack(int smax)
{
    stackbase = (int *)malloc(smax * sizeof(int));
    if (stackbase == NULL)
    {
        stackerr("init error");
    }
    stack = stackbase;
    stack_size = smax;
}

void extend_stack(void)
{
    int *p, new;
    new = stack_size * 2;
    p = (int *)realloc(stackbase, new * sizeof(int));
    if (p == NULL)
    {
        stackerr("extend error");
    }
    stack = p + (stack - stackbase);
    stackbase = p;
    stack_size = new;
}

void print_stack(void)
{
    int *p = stack;
    int n = 0;
    while (p > stackbase)
    {
        p--;
        printf("%d: %d\n", n, *p);
        n++;
    }
}

void push(int x)
{
    if (stack >= stackbase + stack_size)
    {
        extend_stack();
    }
    *stack = x;
    stack++;
}

int pop(void)
{
    if (stack <= stackbase)
    {
        stackerr("Underflow");
    }
    stack--;
    return *stack;
}

void calc(int *a, int c)
{
    int x;
    int y;
    int i;
    int n;
    for (i = 0; i < c; i++)
    {
        n = a[i];
        if (n == -10000)
        {
            y = pop();
            x = pop();
            push(x + y);
        }
        else if (n == -10001)
        {
            y = pop();
            x = pop();
            push(x * y);
        }
        else if (n == -10002)
        {
            printf("%d\n", pop());
            break;
        }
        else
        {
            push(n);
        }
    }
}

int main(int argc, char* argv[])
{
    int i;
    char* arg;
    int x;
    int y;

    init_stack(1);
    for (i = 1; i < argc; i++)
    {
        arg = argv[i];
        if (strcmp(arg, "+") == 0)
        {
            y = pop();
            x = pop();
            push(x + y);
        }
        else if (strcmp(arg, "x") == 0)
        {
            y = pop();
            x = pop();
            push(x * y);
        }
        else if (strcmp(arg, "p") == 0)
        {
            printf("%d\n", pop());
        }
        else
        {
            push(atoi(arg));
        }
    }

    return EXIT_SUCCESS;
}
