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
#include <bits/stdc++.h>
using namespace std;

const int MAX = 250 * 1024 * 1024 / 2;

short B[MAX], H[1000], I[502], N[1001], S[1000];
int m, P[501];

bool szukaj(int a, int b) {
	if (b - a < m) {
		return false;
	}
	for (int i = a, j = 0; i < b; ++i) {
		while (j > -1 && S[j] != B[i]) {
			j = N[j];
		}
		++j;
		if (j == m) {
			return true;
		}
	}
	return false;
}

int main() {
int a, a2, b, b2, c, n, p;
	scanf("%d %d", &n, &m);
	a = 0;
	for (int i = 1; i <= n; ++i) {
		I[i] = a;
		scanf("%d", &b);
		while (b--) {
			scanf("%hd", H + a);
			++a;
		}
	}
	I[n + 1] = a;
	for (int i = 1; i <= n; ++i) {
		for (int j = I[i]; j < I[i + 1]; ++j) {
			P[i] += I[H[j] + 1] - I[H[j]];
		}
	}
	for (int i = 0; i < m; ++i) {
		scanf("%hd", S + i);
	}
	N[0] = a = -1;
	for (int i = 1; i <= m; ++i) {
		while (a > -1 && S[a] != S[i - 1]) {
			a = N[a];
		}
		++a;
		if (i == m || S[i] != S[a]) {
			N[i] = a;
		} else {
			N[i] = N[a];
		}
	}
	B[0] = n = 1;
	a = 0;
	b = 1;
	p = I[2] - I[1];
	while (true) {
		if (szukaj(a, b)) {
			printf("%d\n", n);
			return 0;
		}
		if (b - a + p > MAX) {
			puts("-1");
			return 0;
		}
		if (a == 0) {
			a2 = b2 = MAX - p;
		} else {
			a2 = b2 = 0;
		}
		p = 0;
		for (int i = a; i < b; ++i) {
			c = I[B[i] + 1] - I[B[i]];
			memcpy(B + b2, H + I[B[i]], c * sizeof(short));
			b2 += c;
			p += P[B[i]];
		}
		a = a2;
		b = b2;
		++n;
	}
	return 0;
}