#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#define MAX 100000

// Stack for storing tag names
typedef struct {
    char *arr[MAX];
    int top;
} Stack;

void init(Stack *s) { s->top = -1; }
int isEmpty(Stack *s) { return s->top == -1; }

void push(Stack *s, const char *tag) {
    if (s->top < MAX - 1) {
        s->arr[++s->top] = strdup(tag); 
    }
}

char *pop(Stack *s) {
    if (!isEmpty(s)) {
        return s->arr[s->top--];
    }
    return NULL;
}

// Validate tag names: must contain only lowercase letters
int isValidTagName(const char *tag) {
    for (int i = 0; tag[i]; i++) {
        if (!islower(tag[i])) return 0;
    }
    return 1;
}

// Validate one input line
void validateLine(char *line) {
    Stack s;
    init(&s);
    int n = strlen(line);

    for (int i = 0; i < n;) {
        if (line[i] == '<') {
            int j = i + 1;
            int closing = 0;

            if (j < n && line[j] == '/') { 
                closing = 1;
                j++;
            }

            int start = j;
            while (j < n && line[j] != '>') j++;
            if (j == n) { // '>' not found
                printf("Invalid input\n");
                return;
            }

            int len = j - start;
            if (len <= 0 || len > 100) { // empty or too long tag
                printf("Invalid input\n");
                return;
            }

            char tag[105];
            strncpy(tag, &line[start], len);
            tag[len] = '\0';

            if (!isValidTagName(tag)) {
                printf("Invalid input\n");
                return;
            }

            if (!closing) {
                push(&s, tag);
            } else {
                if (isEmpty(&s)) {
                    printf("Unbalanced\n");
                    return;
                }
                char *topTag = pop(&s);
                if (strcmp(topTag, tag) != 0) {
                    printf("Unbalanced\n");
                    free(topTag);
                    return;
                }
                free(topTag);
            }

            i = j + 1; // move after '>'
        } else {
            // normal character (text content)
            i++;
        }
    }

    if (!isEmpty(&s)) {
        printf("Unbalanced\n");
        return;
    }

    printf("Balanced\n");
}

int main() {
    int n;
    if (scanf("%d\n", &n) != 1 || n < 1 || n > 10000) {
        printf("Invalid input\n");
        return 0;
    }

    char line[MAX + 5];
    for (int i = 0; i < n; i++) {
        if (!fgets(line, sizeof(line), stdin)) {
            printf("Invalid input\n");
            return 0;
        }
        line[strcspn(line, "\n")] = 0; // remove newline
        validateLine(line);
    }

    return 0;
}