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

char stack[100][10];
int top = -1; // stack top 
int ip = 0; // input position
char input[100];

void push(const char* s)
{
    strcpy(stack[++top], s);
}

void pop()
{
    top--;
}

void printStack()
{
    for (int i = 0; i <= top; i++)
        printf("%s", stack[i]);
    printf("\n");
}

int reduce()
{
    // ( E ) → E
    if (top >= 2 &&
        strcmp(stack[top - 2], "(") == 0 &&
        strcmp(stack[top - 1], "E") == 0 &&
        strcmp(stack[top], ")") == 0)
    {
        pop(); pop(); pop();
        push("E");
        return 1;
    }

    // id → E
    if (top != -1 && isalpha(stack[top][0]) && strcmp(stack[top], "E") != 0)
    {
        pop();
        push("E");
        return 1;
    }

    // E * E → E
    if (top >= 2 &&
        strcmp(stack[top - 2], "E") == 0 &&
        strcmp(stack[top - 1], "*") == 0 &&
        strcmp(stack[top], "E") == 0)
    {
        pop(); pop(); pop();
        push("E");
        return 1;
    }

    // E + E → E
    if (top >= 2 &&
        strcmp(stack[top - 2], "E") == 0 &&
        strcmp(stack[top - 1], "+") == 0 &&
        strcmp(stack[top], "E") == 0)
    {
        pop(); pop(); pop();
        push("E");
        return 1;
    }

    return 0;
}

int main()
{
    printf("Enter an Expression: ");
    fgets(input, sizeof(input), stdin); // input with spaces

    while (input[ip])
    {
        // ignore spaces
        if (input[ip] == ' ' || input[ip] == '\n')
        {
            ip++;
            continue;
        }

        char temp[2] = { input[ip], '\0' };

        // shift
        push(temp);
        ip++;
        printf("Shift: ");

        // print stack after shifting
        printStack();

        // reduce which in stack
        while (reduce())
        {
            printf("Reduce: ");
            printStack();
        }
    }

    if (top == 0 && strcmp(stack[0], "E") == 0)
        printf("String Accepted\n");
    else
        printf("String Rejected\n");

    return 0;
}