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
#include <cstdio>
#include <vector>
using namespace std;
int n, m, d2, d, minu;
vector <int> bajt, a[501], bajt2;
int tab[1001], t[1001], licz;
int main() {
    scanf("%d%d", &n, &m);
    for (int i = 1; i <= n; i++) {
        scanf("%d", &d);
        for (int j = 1; j <= d; j++) {
            scanf("%d", &d2);
            a[i].push_back(d2);
        }
    }
    for (int i = 1; i <= m; i++)
        scanf("%d", &tab[i]);
    t[0] = -1;
    t[1] = 0;
    for (int i = 2; i <= m; i++) {
        licz = t[i-1];
        while(tab[licz+1] != tab[i]) {
            licz = t[licz];
            if (licz == -1)
                break;
        }
        t[i] = licz + 1;
    }
    bajt.push_back(1);
  /*  for (int i = 1; i <= n; i++) {
        printf("%d ", a[i].size());
    }*/
    while(1) {
    //        printf("yolo");
        minu++;
        licz = 0;
        for (int i = 0; i < bajt.size(); i++) {
            while (tab[licz+1] != bajt[i]) {
                licz = t[licz];
                if(licz == -1)
                    break;
            }
            licz++;
            if (licz == m) {
                printf("%d", minu);
                return 0;
            }
        }
        for (int i = 0; i < bajt.size(); i++) {
            for (int j = 0; j < a[bajt[i]].size(); j++) {
                bajt2.push_back(a[bajt[i]][j]);
            }
            if (bajt2.size() + bajt.size() > 2000000) {
                printf("-1");
                return 0;
            }
        }
            bajt.swap(bajt2);
            vector<int>().swap(bajt2);
    }
}