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
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#include<stdlib.h>
#include<stdio.h>
#include<algorithm>
#include<iostream>
#include<set>
#include<vector>
#include<map>
#include<deque>
typedef long long LL;
typedef unsigned long long ULL;
using namespace std;

map<int,vector<int> > reguly;
vector<int> S;
vector<int> pi;

void calcpi()
{
    	int m,q,k;
        m=S.size();
        pi.resize(S.size()+1,0);
        pi[0]=0;
	pi[1]=0;
        k=0;
        for (q=2;q<=m;q++)
        {
            while (k>0 && S[k]!=S[q-1]) k=pi[k];
            if (S[k] == S[q-1])
            {
                k++;
            }
            pi[q]=k;
        }

}

bool kmp(vector<int> const &tekst)
{
#ifdef DEBUG
	
	printf("kmp:\ntekst: ");
	for(auto it=tekst.begin();it!=tekst.end();it++)
	{
		printf("%d ",*it);
	}
	printf("\n\nS:");
	for(auto it=S.begin();it!=S.end();it++)
	{
		printf("%d ",*it);
	}
	printf("\n\n");

#endif
    	int m,n,i,j;
        m=S.size();
        n=tekst.size();
        i=1;
        j=0;
        while (i<=n-m+1)
        {
            j=pi[j];
            while ((j<m)&&(S[j]==tekst[i+j-1])) j=j+1;
            if (j==m) 
		{
#ifdef DEBUG
			printf("%d\n",i); 
			for(;i<n;i++)
			{
				printf("%d ",tekst[i]);
			}
			printf("\n\n");
#endif
			return true;
		} //wypisanie indeksu, w którym istnieje dopasowanie
            i=i+ max(1,j-pi[j]);
        }
        //printf("%lld: res:%lld\n",MyNodeId(),res);
        return false;
}


int run(deque<int> &q, int p)
{
	deque<int>q2;
	vector<int>v(q.begin(),q.end());
	if(kmp(v)) return p;

	while(q.size()!=0)
	{
		int i = q.front();
		q.pop_front();
		for(auto it=reguly[i].begin();it!=reguly[i].end();it++)
		{
			q2.push_back(*it);
		}
	}
	return run(q2,p+1);
}

int main()
{
        int n,m;
	reguly.clear();
	S.clear();
	pi.clear();
	
        scanf("%d%d",&n,&m);
	for(int i=1;i<=n;i++)
	{	
		int d;
		scanf("%d",&d);
		for(int j=0;j<d;j++)
		{	
			int l;
			scanf("%d",&l);
			reguly[i].push_back(l);
		}
	}
	for (int i=0;i<m;i++)
	{
		int l;
		scanf("%d",&l);
		S.push_back(l);
	}
	calcpi();
	deque<int>q;
	q.push_back(1);
	printf("%d\n",run(q,1));
        return 0;
}