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
#include <cstdio>
int n,m;
#define DLUGOSC 50000000
short int t[DLUGOSC], t2[DLUGOSC], s[1000];
unsigned int P[1010];
short int tabl[2000];
short int off[500];

void prepare() {
	int t = 0;
	P[0] = P[1] = 0;
	for (int i = 1; i <= m; i++) {
		while (t > 0 && (t >= m || s[t] != s[i])) { t=P[t-1]; }
		if (t<m && s[t] == s[i]) { t++; }
		P[i] = t;
	}
}
bool urosnij(short int *so, short int *ta) {
	short int *cp;
	int sp = 0, tp = 0;
	while (so[sp] != -1) {
		cp = &tabl[off[so[sp]-1]];
		while(*cp != -1) {
			ta[tp++] = *(cp++);
			if (tp == DLUGOSC)
				return false;
		}
		sp++;
	}
	ta[tp] = -1;
	return true;
}
bool KMP(const short int *sp) {
	int t = 0;
	int i = 0;
	while (sp[i] != -1 && i < DLUGOSC) {
		while (t > 0 && (s[t] != sp[i] || t >= m)) {
			t=P[t-1];
		}
		if (t < m && s[t] == sp[i]) {
			t++;
		}
		if (t == m) {
			return true;
		}
		i++;
	}
	return false;
}
int main() {
	scanf("%d%d", &n, &m);
	int co = 0;
	for (int i = 0; i < n; i++) {
		int a;
		off[i] = co;
		scanf("%d", &a);
		for (int x = 0; x < a; x++) {
			scanf("%hd", &tabl[co++]);
		}
		tabl[co++] = -1;
	}
	for (int i = 0; i < m; i++) {
		scanf("%hd", &s[i]);
	}
	prepare();
	t[0] = 1;
	t[1] = -1;
	for (int i = 1; i < 100000; i++) {
		if (!urosnij(t, t2))
			break;
		if (KMP(t2)) {
			printf("%d\n", i*2);
			return 0;
		}
		if (!urosnij(t2, t))
			break;
		if (KMP(t)) {
			printf("%d\n", i*2+1);
			return 0;
		}
	}
	printf("-1\n");
}