// editor5
#include <stdio.h>
#include <string.h>
#include <ctype.h>

#define MAXLEN 100000

// Function to check if a line is valid
int is_valid(char *str) {
    for (int i = 0; str[i]; i++) {
        if (str[i] == '<') {
            if (str[i+1] != '/' && !islower(str[i+1])) return 0;
            int j = i+1;
            while (str[j] && str[j] != '>') j++;
            if (str[j] != '>') return 0;
            i = j;
        }
    }
    return 1;
}

// Function to check if tags are balanced
int is_balanced(char *str) {
    int stack[MAXLEN];
    int top = -1;
    char tag[100];
    int tag_len;

    for (int i = 0; str[i]; i++) {
        if (str[i] == '<') {
            if (str[i+1] == '/') { // Closing tag
                int j = i+2;
                tag_len = 0;
                while (str[j] != '>') tag[tag_len++] = str[j++];
                tag[tag_len] = 0;
                if (top == -1 || strcmp(tag, stack[top--])) return 0;
                i = j;
            } else { // Opening tag
                int j = i+1;
                tag_len = 0;
                while (str[j] != '>') tag[tag_len++] = str[j++];
                tag[tag_len] = 0;
                stack[++top] = strcmp(tag); // Push tag onto stack
                i = j;
            }
        }
    }
    return top == -1;
}

int main() {
    int n;
    scanf("%d\n", &n);

    for (int i = 0; i < n; i++) {
        char line[MAXLEN];
        fgets(line, MAXLEN, stdin);
        line[strcspn(line, "\n")] = 0; // Remove newline

        if (!is_valid(line)) {
            printf("Invalid input\n");
        } else if (is_balanced(line)) {
            printf("Balanced\n");
        } else {
            printf("Unbalanced\n");
        }
    }

    return 0;
}