1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

public class eks {
    static List<Integer> current = new ArrayList<>();
    static Map<Integer, List<Integer>> T = new HashMap<>();

    static void create(int origin, String[] values) {
        ArrayList<Integer> list = new ArrayList<>();
        for (int i=1; i<values.length; i++) list.add(Integer.parseInt(values[i]));
        T.put(origin, list);
    }

    static String next() {
        List<Integer> replicated = new ArrayList<>();
        for (Integer c: current) {
            replicated.addAll(T.get(c));
        }
        current = replicated;
        return replicated.toString().replaceAll(", ", " ");
    }

    final static int Max = 20;
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String[] str = in.nextLine().split(" ");
        int n = Integer.parseInt(str[0]);
        int m = Integer.parseInt(str[1]);

        for (int i=1; i<=n; i++) {
            create(i, in.nextLine().split(" "));
        }

        String pattern = in.nextLine();

        if (pattern.equals("1")) {
            System.out.println(1);
        }
        else {
            current.add(1);
            String s = "";
            long time = 1;
            boolean noSolution = false;
            while (!noSolution) {
                ++time;
                s = next();
//                System.out.println(s);
                if (s.contains(pattern)) {
                    System.out.println(time);
                    break;
                }

                if (time > 7000000 || s.length() > 6000000) {
                    noSolution = true;
                    break;
                }
            }

            if (noSolution) System.out.println(-1);
        }

    }
}