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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
#include <cstdio>
#include <vector>
#include <set>
#include <map>
#include <algorithm>

// #define DEBUG

using namespace std;

typedef long long unsigned LLU_t;

const int INF = 1000*1000*1000;
const int MAX_N=505;
const int MAX_M=1010;
const LLU_t BASE=2927;
LLU_t BASE_POW[MAX_M]={};

void genBASEpow() {
	BASE_POW[0]=1;
	for (int i=1; i<MAX_M; ++i)
		BASE_POW[i]=BASE_POW[i-1]*BASE;
}



int N, M;
vector<int> patterns[MAX_N];
int MAX_PATTERN_LEN;

vector<int> SOriginal;

set<int> legitNext[MAX_N];

vector<LLU_t> patternHashes[MAX_N];


//Hashes:
LLU_t hashPattern(vector<int>& pattern) {
	LLU_t res=0;
	
	for (vector<int>::iterator vit=pattern.begin(); vit!=pattern.end(); ++vit) {
		res = res*BASE + *vit;
	}
	
	return res;
}

void genHashTable(vector<int>& pattern, vector<LLU_t>& output) {
	LLU_t res=0;
	
	for (vector<int>::iterator vit=pattern.begin(); vit!=pattern.end(); ++vit) {
		res = res*BASE + *vit;
		output.push_back(res);
	}
}

LLU_t getHash(int from, int to, vector<LLU_t>& hashTab) {
	if (from == 0)
		return hashTab[to];
	
	return hashTab[to] - hashTab[from-1] * BASE_POW[to-(from-1)]; 
}

LLU_t getHash(vector<LLU_t>& hashTab) {
	return getHash(0, hashTab.size()-1, hashTab); 
}




//Patterns preprocessing:

void eliminateUnreachablePatterns() {
	vector<int> queue;
	bool reachable[MAX_N] = {};
	reachable[1] = true;
	queue.push_back(1);
	
	for (int i=0; i<(int)queue.size(); ++i) {
		int parent=queue[i];
		
		for (vector<int>::iterator vit=patterns[parent].begin(); vit!=patterns[parent].end(); ++vit) {
			if (reachable[*vit])
				continue;
			
			reachable[*vit]=true;
			queue.push_back(*vit);
		}
	}
	
	for (int i=1; i<=N; ++i) {
		if (reachable[i] == false)
			patterns[i].clear();
	}
}


void genLegits() {
	set<int> firstElems;
	bool isLast[MAX_N]={};
	
	for (int i=1; i<=N; ++i) {
		if (patterns[i].size()==0)
			continue;
		
		firstElems.insert(patterns[i][0]);
		
		for (int ind=1; ind<(int)patterns[i].size(); ++ind) {
			legitNext[patterns[i][ind-1]].insert(patterns[i][ind]);
		}
		
		isLast[*patterns[i].rbegin()] = true;
	}
	
	for (int i=1; i<=N; ++i) {
		if (isLast[i] == false)
			continue;
		
		for (set<int>::iterator sit=firstElems.begin(); sit!=firstElems.end(); ++sit) {
			legitNext[i].insert(*sit);
		}
	}
}

void genPatternHashes() {
	for (int i=1; i<=N; ++i) {
		if (patterns[i].size()==0)
			continue;
		
		genHashTable(patterns[i], patternHashes[i]);
	}
	return;
}

void findMaxPatternLen() {
	MAX_PATTERN_LEN = 0;
	
	for (int i=1; i<=N; ++i) {
		MAX_PATTERN_LEN = max(MAX_PATTERN_LEN, (int)patterns[i].size());
	}
	return;
}



//DFS:

struct SData {
	int order;
	vector<int> S;
	vector<LLU_t> Shash;
};

vector<SData*> bfsQueue;
set<LLU_t> queued;

void gatherBFSdata(map<int, set<int> > (&dynArr)[2*MAX_M], int pos, pair<int, int> startingPoint, vector<int>& S, int order) {
	int cameViaPattern = startingPoint.first;
	int prevPattern = startingPoint.second;
	
	S.push_back(cameViaPattern);
	
	#ifdef DEBUG
		fprintf(stderr, "gatherBFSdata\n");
	#endif
	
	if (prevPattern==0) {
		#ifdef DEBUG
			for (int i=S.size()-1; i>=0; --i) {
				fprintf(stderr, "%d, ", S[i]);
			}
			fprintf(stderr, "\n");
		#endif
		
		SData* Sd = new SData();
// 		vector<int> newS;
		for (int i=S.size()-1; i>=0; --i) {
			Sd->S.push_back(S[i]);
		}
		
		genHashTable(Sd->S, Sd->Shash);
		Sd->order = order+1;
		
		if (queued.find(getHash(Sd->Shash)) == queued.end()) {
			queued.insert(getHash(Sd->Shash));
			bfsQueue.push_back(Sd);
		} else {
			delete Sd;
		}
		
		S.pop_back();
		return;
	}
	
	int prevPos = pos-patterns[cameViaPattern].size();
	
// 	pair<multimap<int,int>::iterator, multimap<int,int>::iterator> range = dynArr[prevPos].equal_range(prevPattern);
	for (set<int>::iterator sit=dynArr[prevPos][prevPattern].begin(); sit!=dynArr[prevPos][prevPattern].end(); ++sit) {
		gatherBFSdata(dynArr, prevPos, make_pair(prevPattern, *sit), S, order);
	}
	
	S.pop_back();
	return;
}


void clearAfterBFS(int lastQ) {
	//TODO: clear pointers
}

int BFS() {
	SData* Sd = new SData();
	
	for (int i=0; i<(int)SOriginal.size(); ++i) {
		Sd->S.push_back(SOriginal[i]);
	}
	genHashTable(Sd->S, Sd->Shash);
	Sd->order=1;
	
	queued.insert(getHash(Sd->Shash));
	bfsQueue.push_back(Sd);
	
	
	
	map<int, set<int> > dynArr[2*MAX_M]={};
	
	
	for (int q=0; q<(int)bfsQueue.size(); ++q) {
		Sd = bfsQueue[q];
		
		if (Sd->S.size()==1 && Sd->S[0]==1) {
			clearAfterBFS(q);
			return Sd->order;
		}
		
		//Initialize dynamic
		for (int i=1; i<=N; ++i) {
			for (int whatIsAtSzero=0; whatIsAtSzero<=(int)(patterns[i].size())-1; ++whatIsAtSzero) {
				int matchLen = min(Sd->S.size(), patterns[i].size()-whatIsAtSzero);
				int SFrom = 0;
				int STo = matchLen-1;
				int patFrom = whatIsAtSzero;
				int patTo = patFrom + matchLen-1;
				
				#ifdef DEBUG
					fprintf(stderr, "      pattern=%d  ;  matchLen=%d  ;  patFrom=%d  ;  patTo=%d  ;  SFrom=%d  ;  STo=%d  ;  patternHash=%llu   ;   Shash=%llu\n",
						i,
						matchLen,
						patFrom,
						patTo,
						SFrom,
						STo,
						getHash(patFrom, patTo, patternHashes[i]),
						getHash(SFrom, STo, Sd->Shash)
					);
				#endif
				
				if (getHash(patFrom, patTo, patternHashes[i]) == getHash(SFrom, STo, Sd->Shash)) {
	// 				dynArr[Sto].insert(make_pair(i, set<int>());
					dynArr[STo][i].insert(0);
				}
			}
		}
		
		#ifdef DEBUG
			fprintf(stderr, "DynArr:\n");
		#endif
		
		for (int pos=0; pos<(int)(Sd->S.size())-1; ++pos) {	//when we reach pos=Sd->S.size()-1 we already have all needed records
			#ifdef DEBUG
				fprintf(stderr, "  pos=%d -> \n", pos);
			#endif
			
	// 		for (multimap<int, int>::iterator mit=dynArr[pos].begin(); mit!=dynArr[pos].end(); ++mit) {
			for (map<int, set<int> >::iterator mit=dynArr[pos].begin(); mit!=dynArr[pos].end(); ++mit) {
	// 			for (set<int>::iterator sit=mit->second.begin(); sit!=mit->second.end(); ++sit) {
					#ifdef DEBUG
	// 					fprintf(stderr, "    (%d, %d) \n", mit->first, *sit);
						fprintf(stderr, "    (%d) \n", mit->first);
					#endif
					
					int cameViaPattern = mit->first;
					
					for (set<int>::iterator legit=legitNext[cameViaPattern].begin(); legit!=legitNext[cameViaPattern].end(); ++legit) {
						int goingNextViaPattern = (*legit);
						int matchLen = min(patterns[goingNextViaPattern].size(), Sd->S.size()-(pos+1));
						int patFrom = 0;
						int patTo = matchLen-1;
						int SFrom = pos+1;
						int STo = (pos+1)+(matchLen-1);
						
						#ifdef DEBUG
							fprintf(stderr, "      pattern=%d  ;  matchLen=%d  ;  patFrom=%d  ;  patTo=%d  ;  SFrom=%d  ;  STo=%d  ;  patternHash=%llu   ;   Shash=%llu\n",
								goingNextViaPattern,
								matchLen,
								patFrom,
								patTo,
								SFrom,
								STo,
								getHash(patFrom, patTo, patternHashes[goingNextViaPattern]),
								getHash(SFrom, STo, Sd->Shash)
							);
						#endif
						
						if (getHash(patFrom, patTo, patternHashes[goingNextViaPattern]) != getHash(SFrom, STo, Sd->Shash))
							continue;
						
						//We have a match:
	// 					dynArr[pos+patterns[goingNextViaPattern].size()].insert(make_pair(goingNextViaPattern, cameViaPattern));
						dynArr[pos+patterns[goingNextViaPattern].size()][goingNextViaPattern].insert(cameViaPattern);
					}
	// 			}
			}
			#ifdef DEBUG
				fprintf(stderr, "\n");
			#endif
		}
		
		
		for (int i=0; i<MAX_PATTERN_LEN+2; ++i) {	//+2 just to be sure :P
			int pos = Sd->S.size()-1+i;
			
	// 		for (multimap<int, int>::iterator mit=dynArr[pos].begin(); mit!=dynArr[pos].end(); ++mit) {
			for (map<int, set<int> >::iterator mit=dynArr[pos].begin(); mit!=dynArr[pos].end(); ++mit) {
				for (set<int>::iterator sit = mit->second.begin(); sit!=mit->second.end(); ++sit) {
					vector<int> newS;
					gatherBFSdata(dynArr, pos, make_pair(mit->first, *sit), newS, Sd->order);
				}
			}
		}
		
		int limit = min((int)(Sd->S.size()+MAX_PATTERN_LEN+2), 2*MAX_M);
		for (int i=0; i<limit; ++i)
			dynArr[i].clear();
		
		
		delete Sd;
	}
	
	return INF;
}





//Debugs:
void debugPrintPatterns() {
	for (int i=1; i<=N; ++i) {
		if (patterns[i].size()==0)
			continue;
		
		fprintf(stderr, "  %d -> ", i);
		
		for (vector<int>::iterator vit=patterns[i].begin(); vit!=patterns[i].end(); ++vit) {
			fprintf(stderr, "%d, ", (*vit));
		}
		
		fprintf(stderr, "\n");
	}
}

void debugPrintLegitNext() {
	for (int i=1; i<=N; ++i) {
		if (patterns[i].size()==0)
			continue;
		
		fprintf(stderr, "  %d -> ", i);
		
		for (set<int>::iterator sit=legitNext[i].begin(); sit!=legitNext[i].end(); ++sit) {
			fprintf(stderr, "%d, ", (*sit));
		}
		
		fprintf(stderr, "\n");
	}
}





int main() {
	genBASEpow();
	
	scanf("%d %d", &N, &M);
	
	int l, tmp;
	for (int i=1; i<=N; ++i) {
		scanf("%d", &l);
		
		for (int j=0; j<l; ++j) {
			scanf("%d", &tmp);
			patterns[i].push_back(tmp);
		}
	}
	
	for (int i=1; i<=M; ++i) {
		scanf("%d", &tmp);
		SOriginal.push_back(tmp);
	}
	
	#ifdef DEBUG
		fprintf(stderr, "Before elimination:\n");
		debugPrintPatterns();
	#endif
	
	eliminateUnreachablePatterns();
	
// 	#ifdef DEBUG
// 		fprintf(stderr, "Before merging:\n");
// 		debugPrintPatterns();
// 	#endif
// 	
// // 	mergePatterns();
// 	
	#ifdef DEBUG
		fprintf(stderr, "After merging:\n");
		debugPrintPatterns();
	#endif
	
	genLegits();
	
	#ifdef DEBUG
		fprintf(stderr, "LegitNext:\n");
		debugPrintLegitNext();
	#endif
	
	genPatternHashes();
	
	findMaxPatternLen();
	
	#ifdef DEBUG
		fprintf(stderr, "SOriginal:\n  ");
		for (int i=0; i<(int)SOriginal.size(); ++i) {
			fprintf(stderr, "%d, ", SOriginal[i]);
		}
		fprintf(stderr, "\n");
	#endif
	
	
	//Finally do some stuff:
	
	set<LLU_t> hashStorage;
	int res = BFS();
	
	if (res==INF)
		printf("-1\n");
	else
		printf("%d\n", res);
	
	return 0;
}