Evaluation Order of Assignments (Small)

Given assignment statements where each expression is a function call, decide whether some order evaluates every variable, which fails exactly when a dependency cycle exists.

Medium4GraphTopological sortDFSImplementationInterviewNo attempts yetTime limit5sMemory limit1024 MB

Problem

You are given an unordered list of assignment statements. Write a program that decides whether the statements can be put in some order in which all variables can be evaluated.

In this problem an assignment statement consists of an assignment variable, an assignment operator, and an expression, in that order. Statements are evaluated one at a time, in the order you choose for them. A variable can be evaluated if and only if it has been the assignment variable of an earlier statement.

To keep the problem simple, every expression is a single function call. A function takes any number of arguments, including zero. A call with zero arguments is always valid, and a call with arguments is valid as long as every variable used as an argument can be evaluated.

For example, consider this list of assignment statements.

a=f(b,c)
b=g()
c=h()

This order makes every statement valid.

b=g()
c=h()
a=f(b,c)

There are two reasons. g() and h() depend on no variable, so b and c can be evaluated. The expression for a depends on b and c, and both can be evaluated, so a can be evaluated too.

The order below is not valid.

b=g()
a=f(b,c)
c=h()

f(b,c) takes the variable c as an argument, but at that point c has not been the assignment variable of any statement yet.

Another example is a=f(a). The expression f(a) depends on the variable a itself, so this statement can never be evaluated.

Input

The first line contains the number of test cases TT. The first line of each test case contains the number of assignment statements NN, and NN lines follow, one assignment statement per line.

Each assignment statement consists of three parts, the assignment variable, the assignment operator, and the expression, with no spaces in between. The assignment operator is always =. Every expression consists of a function name, then (, then zero or more comma-separated variable names, then ). All variable names and function names consist of one or more lowercase English letters. No variable has the same name as a function. No variable appears more than once as the assignment variable. A variable may appear in several function calls, and more than once inside a single call, and the same function may appear several times.

Limits

  • 1T201 \le T \le 20
  • Every function takes between 0 and 10 arguments, inclusive.
  • Every variable name consists of between 1 and 20 lowercase English letters.
  • 1N1001 \le N \le 100

Output

For each test case, print one line in the form Case #x: y, where xx is the test case number starting from 1, and yy is GOOD if all variables can be evaluated and BAD otherwise.