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
#include <iostream>
#include <stdio.h>
#include <vector>

using namespace std;

int main() {
	int n, m;
	scanf("%d%d", &n, &m);
	vector<int> l[n];
	int srK = 0;
	for (int i = 0; i < n; i++) {
		int k;
		scanf("%d", &k);
		srK += k;
		while (k--) {
			int a;
			scanf("%d", &a);
			a--;
			l[i].push_back(a);
		}
	}
	srK /= n;
	int S[m];
	unsigned int wzHash = 0;
	unsigned int _pot = 1;
	for (int i = 0; i < m; i++) {
		scanf("%d", &S[i]);
		S[i]--;
		wzHash += (S[i] + 1) * _pot;
		_pot *= 2137u;
	}
	//printf("!!!: %d\n", wzHash);
	if (m == 1 && S[0] == 0) {
		puts("1");
		return 0;
	}
	vector<int> _pop;
	_pop.push_back(0);
	vector<int> _akt;
	vector<int>* pop = &_pop;
	vector<int>* akt = &_akt;
	for (int it = 0; it < 30; it++) {
		if (pop->size() * srK >= 15000000) break;
		vector<unsigned int> hasze;
		unsigned int aktH = 0;
		unsigned int pot = 1;
		//cout << "TU1" << endl;
		for (int i = 0; i < pop->size(); i++) {
			for (int j = 0; j < l[pop->at(i)].size(); j++) {
				akt->push_back(l[pop->at(i)][j]);
				// cout << l[pop->at(i)][j] << " ";
				aktH += (l[pop->at(i)][j] + 1) * pot;
				hasze.push_back(aktH);
				//cout << aktH << " ";
				pot *= 2137u;
			}
		}
		//cout << endl;
		//cout << "TU2" << endl;
		pot = 1;
		if (m - 1 < hasze.size() && hasze[m - 1] == wzHash) {
			printf("%d\n", it + 2);
			return 0;
		}
				//cout << "TU3" << endl;
		pot = 2137;
		//printf("!!!!!!!\n");
		for (int i = m; i < hasze.size(); i++) {
			//printf("%d ", hasze[i] - hasze[i - m]);
			if ((unsigned int)(hasze[i] - hasze[i - m]) == wzHash * pot) {
				printf("%d\n", it + 2);
				return 0;
			}
			pot *= 2137u;
		}
		//printf("\n!!!!!!!!\n");
		//	cout << "TU4" << endl;
		swap(pop, akt);
		//	cout << "TU5" << endl;
		akt->clear();
	}
	puts("-1");
	return 0;
}