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

char stack[100][10];
int top = -1;
int idx = 0;
char input[100];

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

void pop() {
    top--;
}

// Print stack with spaces between symbols (matches expected output)
void printStack() {
    for (int i = 0; i <= top; i++) printf("%s ", stack[i]);
    printf("\n");
}

int reduce() {
    // Rule 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;
    }
    // Rule 2: 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;
    }
    // Rule 3: 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;
    }
    // Rule 4: E → id
    if (top != -1 && stack[top][0] >= 'a' && stack[top][0] <= 'z') {
        pop();
        push("E");
        return 1;
    }
    return 0;
}

int main() {
    printf("Enter an Expression:\n");
    fgets(input, sizeof(input), stdin); // fgets allows spaces in input

    while (input[idx]) {
        // Skip whitespace characters
        if (isspace(input[idx])) {
            idx++;
            continue;
        }

        char temp[2] = {input[idx], '\0'};
        push(temp);
        idx++;

        printf("Shift: ");
        printStack();

        while (reduce()) {
            printf("Reduce: ");
            printStack();
        }
    }

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

    return 0;
}