Through a Maze Darkly

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 MB

Problem

A maze is made of NN rooms joined by corridors. The rooms are numbered 11 to NN, and every room is a circle. The corridors satisfy these conditions.

  • One corridor joins two different rooms.
  • No two corridors join the same pair of rooms.
  • Every room has at least one corridor joined to it.

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 QQ queries. Each query names one starting room rr. Find the largest number of corridors you can walk through, starting from room rr with your right hand on the wall, until you come back to room rr for the first time.

Input

The first line contains an integer NN (2N1000002 \le N \le 100\,000).

Each of the next NN lines describes the layout of the maze. The ii-th of these lines contains kk, the number of corridors joined to room ii, followed by the room numbers c1 c2  ckc_1\ c_2\ \dots\ c_k that those corridors lead to. The room numbers are listed in clockwise order as seen from room ii.

For example, if the line for room ii is 3 4 2 7, then room ii 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 QQ (1QN1 \le Q \le N).

Each of the last QQ lines contains one starting room number rr (1rN1 \le r \le N). The same room number never appears twice.

Let MM be the total number of corridors in the maze, which is half the sum of all kk values. MM does not exceed 200000200\,000.

Output

Print QQ lines, one answer per query, in the order the queries are given. Line ii holds the answer to query ii, the largest number of corridors walked from room rr until the first return to room rr.