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
131
132
133
134
135
136
137
138
139
#include <cstdio>
#include <vector>


using namespace std;
 

bool isSubset(vector<int> a, int b[], int size_a, int size_b)
{/*
			for(std::vector<int>::size_type i = 0; i != a.size(); i++) {
				printf("%d ", a[i]);
			}
			
			printf("\n");
	*/
	if(size_b > size_a){
		return false;
	}
	
	int current_cell = 0;
	bool checking = false;
	
	for(int i=0; i<size_a; i++){
		
		if(a[i] == b[current_cell]){
			current_cell++;
		}else{
			current_cell = 0;
			if(a[i] == b[current_cell]){
				current_cell++;
			}
		}
	
		if(current_cell >= size_b){
			return true;
		}
	}
	
	return false;
	
}


int main(){
	
	int num_types;
	int ** sequences;
	int * sizes;
	int * s;
	int size_s;
	int minute = 1;
	bool can_end = true;
	
	//input
	
	scanf("%d", &num_types);
	scanf("%d", &size_s);

	sequences = new int*[num_types];
	sizes = new int[num_types];
	
	for(int i=0; i<num_types; i++){
		int size;
		scanf("%d", &size);
		
		sequences[i] = new int[size];
		sizes[i] = size;
		
		for(int j=0; j<size; j++){
			int tmp;
			scanf("%d", &tmp);
			sequences[i][j] = tmp;
		}
	}

	s = new int[size_s];
	for(int i=0; i<size_s; i++){
		int tmp;
		scanf("%d", &tmp);
		s[i] = tmp;
	}	
		
	/*
	printf("%d ",num_types);
	printf("%d\n",size_s);
	for(int i=0; i<num_types; i++){
		for(int j=0; j<sizes[i]; j++){
			printf("%d ", sequences[i][j]);
		}
		printf("\n");
	}
	
	for(int i=0; i<size_s; i++){
		printf("%d ",s[i]);
	}
	*/	
	
	//algorithm
	
    vector<int> cells(sequences[0], sequences[0] + sizes[0]);	
	vector<int> old_cells;
	
	
	while(true){
		
		minute++;
		
		if(minute > 500){
			printf("NIE");
			break;
		}
		
		if(isSubset(cells,s, cells.size(), size_s)){
			printf("%d", minute);
			break;
		}
			
		old_cells = cells;	
		cells.clear();
		
		for(std::vector<int>::size_type i = 0; i != old_cells.size(); i++) {
			int cell = old_cells[i] - 1;
			for(int c=0;c<sizes[cell]; c++){
				cells.push_back(sequences[cell][c]);
			}
		}
			
	}
	
	//memory deallocattion
	
	delete [] s;
	
	for (int i = 0; i < num_types; ++i)
		delete [] sequences[i];
	
	delete [] sequences;
	delete [] sizes;
}