/* Class: COP3530
 * Date: Feb 24, 2006
 * Instructor: Arup Guha
 * TA: Adam Campbell
 *
 * Recitation #4, Problem #2
 **/

import java.io.*;
import java.util.*;

public class Rec4Prob2{

	/* I have main throw exception so I don't need the try/catch blocks everywhere when reading in from the file.
	 * In general, this is not good programming practice, but for these simple problems we are more interested in the
	 *   algorithm.
	 **/
	public static void main(String[] args) throws Exception{

		BufferedReader userInputReader, fileReader;
		String fileName;
		StringTokenizer tokenizer;
		int[][] adj; // the adjacency matrix
		int[] dist;
		boolean isValid;
		int n, s;

		// initialize the BufferedReader to read from standard input
		userInputReader = new BufferedReader(new InputStreamReader(System.in));

		// prompt the user for the file name, and get the file name from the user
		System.out.print("Please enter the file name: ");
		fileName = userInputReader.readLine();

		// open up the input file
		fileReader = new BufferedReader(new FileReader(fileName));

		// read n, number of vertices
		n = Integer.parseInt(fileReader.readLine());

		adj = new int[n][n];
		dist = new int[n];

		// initialize the matrix with big values
		for(int i = 0; i < n; i++){
			for(int j = 0; j < n; j++){
				adj[i][j] = Integer.MAX_VALUE/2;
			}
		}

		// read in the edges
		for(int fromVert = 0; fromVert < n; fromVert++){

			tokenizer = new StringTokenizer(fileReader.readLine());

			// loop through connections to curVert
			while(tokenizer.hasMoreTokens()){
				// subtract one to zero index the vertices (the input file has them from 1 to n, we want from 0 to n-1)
				int toVert = Integer.parseInt(tokenizer.nextToken()) - 1;
				adj[fromVert][toVert] = 1;
			}

		}

		// set diagonal to zero
		for(int i = 0; i < n; i++){
			adj[i][i] = 0;
		}

		// run Floyd-Warshall's all pairs shortest path algorithm on the graph
		for(int mid = 0; mid < n; mid++){
			for(int start = 0; start < n; start++){
				for(int end = 0; end < n; end++){
					if(adj[start][end] > adj[start][mid]+adj[mid][end]){
						adj[start][end] = adj[start][mid]+adj[mid][end];
					}
				}
			}
		}

		s = Integer.parseInt(fileReader.readLine());

		// loop through all student answers
		while(s-- > 0){

			tokenizer = new StringTokenizer(fileReader.readLine());

			for(int i = 0; i < n; i++){
				// subtract one because we zero-index things
				dist[i] = adj[0][Integer.parseInt(tokenizer.nextToken()) - 1];
			}

			isValid = true;

			for(int i = 1; i < n; i++){
				if(dist[i-1] > dist[i]) isValid = false;
			}

			if(isValid){
				System.out.println("CORRECT!");
			}else{
				System.out.println("SORRY, NOT A VALID SEARCH!");
			}

		}

	}

}
