Museum Tour
Time limit1sMemory limit512 MB
Given a connected graph with max degree 3 and a fixed cyclic door order per room, count starting rooms whose edge-following walk eventually traverses every corridor.
- Level
Hard8 of 10
- Topics
- Graph, Simulation, Implementation, DFS
- Solved
- No attempts yet
Problem
A large museum has many rooms and many corridors. Planning a tour through it takes real work, so the museum put a simple rule on its signs and asks visitors to follow it.
If room has doors leading through corridors to other rooms, those doors and the matching corridors carry numbers that are used only inside that room. The rule has two parts.
- In the room where the tour starts, leave through door .
- If you entered a room through door , leave through the door with the next number: door when , and door when .
The picture below shows a tour that starts in room and passes rooms in this order, walking through every corridor at least once.

Exhibits hang in the corridors as well as in the rooms. What matters is whether a visitor who follows the rule, does not get bored, and walks long enough finally passes through every corridor at least once. Call a room a good starting room when a tour that begins there does exactly that.
The door numbers are already fixed and are given in the input. Count the good starting rooms.
At most 3 corridors leave each room, and the whole museum is connected: you can walk between any two rooms, possibly passing through other rooms on the way. All corridors leaving one room lead to different rooms.
Input
The input contains several test cases. The first line contains the number of test cases ().
Each test case begins with a line containing the number of rooms (). The next lines describe the doors, one line per room, in order of the door numbers. Line starts with the number of doors (), followed by integers . Here is the room that door of room leads to (, , and when ).
All corridors are bidirectional, so if there is a door from room to room , there is a door from room to room as well. The total size of the input does not exceed 50MB.
Output
For each test case, print the number of good starting rooms on one line.