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
#include <cstdio>
#include <vector>
using namespace std;

vector<vector<int> > replications;
vector<int> seq;
vector<int> current;
vector<int> following;

bool found(){
    /*printf("C: ");
    for(int i=0;i<current.size();++i) printf("%d",current[i]+1);
    printf("\nS: ");
    for(int i=0;i<seq.size();++i) printf("%d",seq[i]+1);
    puts("\n");*/
    if(current.size()<seq.size()) return false;
    for(int start=0;start<((int)current.size()-(int)seq.size());++start){
        bool ok=true;
        for(int i=0;i<seq.size();++i){
            if(seq[i]!=current[start+i]){
                ok=false;
                break;
            }
        }
        if(ok) return true;
    }
    return false;
}

int main(){
    int n,m;
    scanf("%d%d",&n,&m);
    replications.resize(n);
    for(int i=0;i<n;++i){
        int l;
        scanf("%d",&l);
        replications[i].resize(l);
        for(int j=0;j<l;++j){
            int x;
            scanf("%d",&x);
            replications[i][j] = x-1;
        }
    }

    seq.resize(m);
    for(int i=0;i<m;++i){
        int x;
        scanf("%d",&x);
        seq[i]=x-1;
    }

    current.push_back(0);
    for(int i=1;i<=18;++i){
        if(found()){
            printf("%d\n",i);
            return 0;
        }
        following.clear();
        for(int j=0;j<current.size();++j){
            for(int k=0;k<replications[current[j]].size();++k) following.push_back(replications[current[j]][k]);
        }
        current = following;
    }
    puts("-1");
    return 0;
}