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
68
69
70
71
72
73
74
75
76
#include <iostream>
#include <vector>
#define REP(a, b) for(int a = 0; a < b; a++)
#define PB push_back
#define SIZE(x) (int)((x).size())
using namespace std;
typedef vector<int> VI;

int main()
{
    ios_base::sync_with_stdio(0);
    int n, m, siz;
    VI start, next;
    cin >> n >> m;
    vector< VI > tab;
    VI sek(m);

    REP(i, n)
    {
        cin >> siz;
        tab.PB(VI(siz));
        REP(j, siz)  cin >> tab[i][j];
    }

    REP(i, m)
    {
        cin >> sek[i];
    }

    int wyn = 1, sq;
    start.PB(1);
    unsigned long long Sstart, Snext;

    while(1)
    {

        wyn++;
        sq = 0;
        next.clear();
        //sizes
        Sstart = SIZE(start);


        //aktualizuje NEXT
        REP(i, Sstart) REP(j, SIZE(tab[start[i]-1])) next.PB(tab[start[i]-1][j]);

        //nadaje START wartosci NEXT i sprawdza czy jest wzorzec
         Snext = SIZE(next);

        start.resize(Snext);
        REP(i, Snext) {
            start[i] = next[i];

             if(start[i] == sek[sq])
                {
                    sq++;
                }
              else if(sq > 0 && sq!=m){
                    sq = 0;
                    i--;
              }
        }


        if(sq == m)
        {
            cout << wyn << endl;
            break;
        }
        if(wyn > (n+2 > m/2 ? n+2 : m/2))
        {
            cout << "-1" << endl;
            break;
        }
    }
}