from collections import defaultdict def build_graph(w, e, connections): # Initialize an empty graph graph = defaultdict(list) # Add all western stations to the graph for i in range(w): graph[i] = [] # Add all eastern stations to the graph for i in range(w, w+e): graph[i] = [] # Add connections to the graph for u, v in connections: graph[u].append(v) graph[v].append(u) return graph def bfs(graph, start): # Initialize visited array and queue for BFS visited = [False] * len(graph) queue = [] # Mark start as visited and add to queue visited[start] = True queue.append(start) # Initialize distance array dist = [0] * len(graph) while queue: # Dequeue a vertex from queue s = queue.pop(0) # Get all adjacent vertices of the dequeued vertex s # If adjacent vertex is not visited yet, then mark it visited # and enqueue it in the queue for i in graph[s]: if not visited[i]: visited[i] = True queue.append(i) # Update the distance of the adjacent vertex dist[i] = dist[s] + 1 return dist def get_average_distance(w, e, connections): # Build the graph graph = build_graph(w, e, connections) # Initialize variables for minimum and maximum distances min_dist = float('inf') max_dist = -1 # Iterate over all possible pairs of start and end vertices for start in range(w): dist = bfs(graph, start) for end in range(w, w+e): if dist[end] > max_dist: max_dist = dist[end] if dist[end] < min_dist: min_dist = dist[end] # Calculate the average distance and return it total_dist = sum([sum(bfs(graph, i)) for i in range(w)]) avg_dist = total_dist / (w*(w-1) + e*(e-1) + 2*w*e) return avg_dist, min_dist, max_dist # Example usage w = 4 e = 3 connections = [(0,4), (1,5), (2,6), (4,5), (5,6)] avg_dist, min_dist, max_dist = get_average_distance(w, e, connections) print("Average distance:", avg_dist) print("Minimum distance:", min_dist) print("Maximum distance:", max_dist)