using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace Way_Points { // A simple Scanner class meant to be similar to java's scanner. // Author: Daniel Wasserman // Date: 2013-05-30 class Scanner { TextReader Reader; public Scanner(TextReader reader) { Reader = reader; } static int Index = 0; static string[] CurrentLine = { }; public bool HasNext() { if (CurrentLine.Length == Index) { try { CurrentLine = Reader.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); Index = 0; return HasNext(); } catch (System.IO.IOException e) { return false; } } return true; } public String Next() { if (HasNext()) return CurrentLine[Index++]; return null; } public int NextInt() { return int.Parse(Next()); } public long NextLong() { return long.Parse(Next()); } public float NextFloat() { return float.Parse(Next()); } public double NextDouble() { return double.Parse(Next()); } } class Program { static List[] g; static void Main(string[] args) { Scanner input = new Scanner(new StreamReader("waypoints.in")); int cases = input.NextInt(); for (int caseOn = 1; caseOn <= cases; caseOn++) { int n = input.NextInt(); int m = input.NextInt(); g = new List[n]; for (int i = 0; i < n; i++) g[i] = new List(); for (int i = 0; i < m; i++) { int a = input.NextInt(); int b = input.NextInt(); g[a].Add(b); } Console.WriteLine("Map #{0}:", caseOn); int r = input.NextInt(); for (int i = 0; i < r; i++) { int ans = 0; int l = input.NextInt(); int at = input.NextInt(); bool impossible = false; for (int j = 0; j < l - 1; j++) { int next = input.NextInt(); int distance = Distance(at, next); ans += Distance(at, next); if (distance < 0) { impossible = true; } at = next; } if (impossible) { Console.WriteLine(-1); } else { Console.WriteLine(ans); } } Console.WriteLine(); } //Console.ReadLine(); } static int Distance(int start, int end) { int[] distance = new int[g.Length]; for (int i = 0; i < g.Length; i++) distance[i] = -1; Queue q = new Queue(); q.Enqueue(start); distance[start] = 0; while (q.Count != 0) { int at = q.Dequeue(); foreach (int neighbor in g[at]) { if (distance[neighbor] == -1) { distance[neighbor] = distance[at] + 1; q.Enqueue(neighbor); } } } return distance[end]; } } }