Evaluation

Given assignment statements where each value depends on argument variables, decide whether some evaluation order resolves every dependency.

Medium4GraphTopological sortDFSNo attempts yetTime limit5sMemory limit512 MB

Problem

You are given an unordered list of assignment statements. Decide whether the statements can be placed in some order in which every statement can be evaluated.

An assignment statement has three parts, in this order: the assignment variable, the assignment operator, and the expression. The statements are evaluated one at a time, in the order you choose for them. A variable can be evaluated only if it has already been the assignment variable of an earlier statement.

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 when every argument variable can be evaluated.

Take 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)

b and c come first because g() and h() depend on no variable, and a follows because f(b,c) depends on b and c, which are both evaluated by then.

The order

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

is not valid, because f(b,c) takes c as an argument and c has not been an assignment variable yet.

A second example is a=f(a). No order works here, because the expression f(a) depends on the variable a that the same statement assigns.

Input

The first line holds the number of test cases, TT. TT test cases follow. The first line of each test case holds an integer NN, the number of assignment statements. The next NN lines each hold one assignment statement.

Each assignment statement has three parts written with no spaces between them: the assignment variable, the assignment operator, and the expression. The assignment operator is always =. Every expression is a function name, then (, then zero or more comma separated variable names, then ). Variable names and function names are made of one or more lowercase English letters. No variable has the same name as a function. No variable appears more than once as an assignment variable. A variable may appear any number of times as an argument, including several times inside the same call, and a function name may appear in several statements.

Limits

  • 1T201 \le T \le 20
  • 1N10001 \le N \le 1000
  • Every function call takes between 0 and 10 arguments, inclusive.
  • Every variable name has between 1 and 20 lowercase English letters, inclusive.

Output

For each test case, print one line of the form Case #x: y, where x is the test case number starting from 1, and y is GOOD if some order evaluates every statement and BAD otherwise.