import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines import numpy as np from scipy.sparse.csgraph import connected_components, dijkstra from scipy.sparse import csr_matrix data = np.fromstring(read(), np.int64, sep=' ') N, M = data[:2] UV = data[2:2+M+M] U = UV[::2] V = UV[1::2] Q = data[2+M+M] A = data[2+M+M+1:] graph = csr_matrix((np.ones_like(U), (U, V)), (N+1, N+1)) _, comp = connected_components(graph) comp_size = np.bincount(comp) dist = dijkstra(graph, directed=False, indices=A)