from collections import defaultdict def dfs(graph, u, visited, path): visited[u] = True path.append(u) if u in graph['W']: graph['WE'].append(path[:]) else: for v in graph[u]: if not visited[v]: dfs(graph, v, visited, path) path.pop() visited[u] = False def calculate_average_distance(graph, options): # calculate paths between western and eastern stations graph['WE'] = [] visited = defaultdict(bool) for w in graph['W']: dfs(graph, w, visited, []) num_paths = len(graph['WE']) # calculate average distance for each option avg_distances = [] for i, (w, e) in enumerate(options): # calculate number of paths and total distance in the complete graph num_paths_total = num_paths + 2 # add two for direct connections to the overpass total_distance = sum(len(path)-1 for path in graph['WE']) total_distance += min(len(graph[w])-1, len(graph[e])-1) # add direct connection to the overpass for path in graph['WE']: if w in path and e in path: total_distance -= len(path)-1 # subtract paths that pass through the overpass num_paths_total -= 1 # calculate average distance avg_distance = total_distance / num_paths_total avg_distances.append(avg_distance) return avg_distances # read input T = int(input()) for t in range(1, T+1): W, E, C = map(int, input().split()) graph = defaultdict(list) for i in range(1, W): u, v = i, int(input()) graph[u].append(v) graph[v].append(u) for j in range(1, E): u, v = j, int(input()) graph['W'].append(u) # add eastern stations to the graph graph['E'].append(v) graph[u].append(v) graph[v].append(u) options = [tuple(map(int, input().split())) for _ in range(C)] # calculate and print output avg_distances = calculate_average_distance(graph, options) print("Case #{}: {}".format(t, " ".join("{:.6f}".format(d) for d in avg_distances)))