A planar maze lists each room's neighbors in clockwise order; for each starting room, find the longest wall-following (right-hand rule) closed walk before returning to the start.
Medium7GraphDFSSimulationImplementationNo attempts yetTime limit2sMemory limit512 MBA maze is made of N rooms joined by corridors. The rooms are numbered 1 to N, and every room is a circle. The corridors satisfy these conditions.
The lights inside the maze are all off, so you cannot see where you are.
One way to move through the maze is to put your right hand on some point of the wall of the starting room and keep walking forward through corridors and other rooms without ever taking your hand off the wall. Walking this way brings you back to the room you started from. Where you put your right hand in the starting room fixes which corridor you take first, so it also fixes the path you follow.
Given the structure of the maze, answer Q queries. Each query names one starting room r. Find the largest number of corridors you can walk through, starting from room r with your right hand on the wall, until you come back to room r for the first time.
The first line contains an integer N (2≤N≤100000).
Each of the next N lines describes the layout of the maze. The i-th of these lines contains k, the number of corridors joined to room i, followed by the room numbers c1 c2 … ck that those corridors lead to. The room numbers are listed in clockwise order as seen from room i.
For example, if the line for room i is 3 4 2 7, then room i has 3 corridors, and they lead to rooms 4, 2, and 7. Because they are listed in clockwise order, the layout is the one in the picture below.

The next line contains an integer Q (1≤Q≤N).
Each of the last Q lines contains one starting room number r (1≤r≤N). The same room number never appears twice.
Let M be the total number of corridors in the maze, which is half the sum of all k values. M does not exceed 200000.
Print Q lines, one answer per query, in the order the queries are given. Line i holds the answer to query i, the largest number of corridors walked from room r until the first return to room r.