P5807 [Template] BEST Theorem / Which Dreamed It

Background

Please note that this problem is slightly different from the real BEST Theorem: the BEST Theorem does not require starting from $1$, and the edge sequence of the circuit is considered up to cyclic isomorphism.

Description

There are $n$ rooms, and each room has several keys that can open the door to a specific room. At the beginning, you are in room $1$. Each time you arrive at a room, you may choose one key in that room, go to the room corresponding to that key, and throw that key into the trash bin. You want to finally return to room $1$, and have all the keys in the trash bin. You need to count the number of valid plans, modulo $10^6 + 3$. Two plans are different if and only if the order of using keys is different. Note that every key is distinct. Originally BZOJ3659.

Input Format

**This problem contains multiple test cases.** The first line contains an integer $T$, the number of test cases. For each test case: The first line contains an integer $n$. The next $n$ lines describe the rooms. Line $i$ describes room $i$: First a number $s$, the number of keys in this room, followed by $s$ numbers, each describing which room’s door that key can open.

Output Format

For each test case, output one integer per line, the answer modulo $10^6 + 3$.

Explanation/Hint

### Sample Explanation * Sample $1$ In the first test case, there are no keys, so the number of plans is $1$. In the second test case, you cannot use the key in the second room, so the number of plans is $0$. * Sample $2$ It is enough to use up all the keys; you do not necessarily need to visit all rooms. * Sample $3$ Before taking modulo, the answers for the first three test cases are $2,190080,49476320425715737559040000000$, respectively. ### Constraints For $50\%$ of the testdata, $n \le 4$, $\sum s \le 30$. For $100\%$ of the testdata, $1 \le T \le 15$, $1 \le n \le 100$, $0 \le \sum s \le 3141592$. Strengthened on 2021/5/14 by [SSerxhs](https://www.luogu.com.cn/user/29826) & [滑大稽](https://www.luogu.com.cn/user/203743). Translated by ChatGPT 5