This page is still under construction.

Parts of this page are still being built. What you see may change.

Museum Tour

Time limit1sMemory limit512 MB

Summary
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 vv has dd doors leading through corridors to other rooms, those doors and the matching corridors carry numbers 1,2,…,d1, 2, \dots, d that are used only inside that room. The rule has two parts.

  • In the room where the tour starts, leave through door 11.
  • If you entered a room through door ii, leave through the door with the next number: door i+1i + 1 when i<di < d, and door 11 when i=di = d.

The picture below shows a tour that starts in room 11 and passes rooms 1,2,3,4,5,61, 2, 3, 4, 5, 6 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 tt (t≤100t \le 100).

Each test case begins with a line containing the number of rooms nn (3≤n≤1053 \le n \le 10^5). The next nn lines describe the doors, one line per room, in order of the door numbers. Line ii starts with the number of doors dd (1≤d≤31 \le d \le 3), followed by dd integers r1,r2,…,rdr_1, r_2, \dots, r_d. Here rjr_j is the room that door jj of room ii leads to (1≤rj≤n1 \le r_j \le n, rj≠ir_j \ne i, and rj≠rkr_j \ne r_k when j≠kj \ne k).

All corridors are bidirectional, so if there is a door from room xx to room yy, there is a door from room yy to room xx 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.

Examples2

  1. Example 1

    Input
    2
    6
    3 4 2 3
    3 5 1 3
    3 6 1 2
    1 1
    1 2
    1 3
    4
    2 2 4
    2 1 3
    2 2 4
    2 1 3
    
    Expected output
    0
    4
    
  2. Example 2

    Input
    1
    6
    3 4 2 3
    3 5 3 1
    3 6 1 2
    1 1
    1 2
    1 3
    
    Expected output
    6