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

const static uint32_t MAX_N = 1000;
const static uint32_t MAX_M = 1000;

list<uint32_t> E[MAX_N + 1];
uint32_t S[MAX_M];
bool exists[MAX_N + 1];

stack<uint32_t> Stack;
vector<uint32_t> V1, V2;

int main() {
	uint32_t n, m, l, h;
	scanf("%lu %lu", &n, &m);
	for (uint32_t i = 1; i <= n; ++i) {
		scanf("%lu", &l);
		for (uint32_t j = 0; j < l; ++j) {
			scanf("%lu", &h);
			E[i].push_back(h);
		}
	}

	Stack.push(1);
	exists[1] = true;

	while(!Stack.empty()) {
		uint32_t v = Stack.top(); Stack.pop();
		for (uint32_t w: E[v]) {
			if (!exists[w]) {
				exists[w] = true;
				Stack.push(w);
			}
		}
	}

	for (uint32_t i = 0; i < m; ++i) {
		scanf("%lu", S + i);
		if (!exists[S[i]]) {
			printf("-1");
			return 0;
		}
	}

	uint32_t level = 0;
	V1.reserve(m * m);
	V2.reserve(m * m);

	V1.push_back(1);
	while(level < 1000) {
		++level;
		for (uint32_t i = 0; i < V1.size() - m + 1; ++i) {
			uint32_t j = 0;
			while (j < m && S[j] == V1[i + j]) j++;
			if (j == m) {
				printf("%lu", level);
				return 0;
			}
		}
		for(uint32_t v: V1) {
			V2.insert(V2.end(), E[v].begin(), E[v].end());
		}
		V1 = V2;
	}

	printf("-1");
	return 0;
}