Under construction

Still being built. Things may change

Subway in Seoul

Interview

Time limit2sMemory limit128 MB

Summary
Given up to 10 subway lines, each listing stations (0 is the start), find the minimum number of transfers to reach a destination station.
Level

Medium6 of 10

Topics
Graph, BFS, Hash map, Implementation
Solved
No attempts yet

Problem

Mr.Goofcode, an American who has just arrived in Korea, was excited about traveling to Seoul, the capital of Korea. But when he arrived at Seoul Station on the airport railway, he was shocked by the complicated Seoul subway map. Every station in Seoul, including Seoul Station, had to be identified by numbers rather than names, and there were so many subway lines in operation that computing an optimal route was difficult.

In a panic, Mr.Goofcode asked you for help, since the two of you had long exchanged letters by email. Because Mr.Goofcode had helped you before, you decide to build a subway map application for him. But the picky Mr.Goofcode hates walking, so you want the application to minimize the number of subway transfers it suggests.

Given the subway map, find the minimum number of transfers Mr.Goofcode needs to reach his destination. The station number of Seoul Station, his starting station, is always 0.

A subway 'line' is the set of stations you can travel through on one kind of subway without transferring to another. A subway 'station' is an element of a subway line, a vertex the subway can visit. Each station can be represented as connected by edges, and the subway can move only through these edges. The subway can move in both directions.

Input

The first line gives the number of subway lines in Seoul, N(1≤N≤10)N(1 \le N \le 10).

From the second line onward, for line 1 through line NN in order, one line gives the number of stations K(1≤K≤10)K(1 \le K \le 10) on that line and the station numbers aN1,aN2,aN3,…,aNKa_{N1}, a_{N2}, a_{N3}, \dots, a_{NK} that the line contains. All station numbers are distinct and are guaranteed to be integers between 0 and 232−12^{32}-1 inclusive.

The last line of the input gives the destination station number.

Note that some subway lines may be circular. For a circular line, the input gives the station numbers it contains in the form a1,a2,a3,…,aK−1,a1a_1, a_2, a_3, \dots, a_{K-1}, a_1. (See sample 2.)

Output

Output the minimum number of transfers from the starting station (Seoul Station) to the destination station on one line. If the destination cannot be reached, output -1.

Examples2

  1. Example 1

    Input
    3
    3 0 2 3
    4 2 5 7 10
    2 10 8
    8
    
    Expected output
    2
    
  2. Example 2

    Input
    3
    4 1 2 3 1
    5 0 9 4 7 99
    4 8 10 7 9
    1
    
    Expected output
    -1