Problem Statement
You are given a weighted undirected graph G with N vertices, numbered 1 to N. Initially, G has no edges.
You will perform M operations to add edges to G. The i-th operation (1≤i≤M) is as follows:
You are given a subset of vertices Si={Ai,1, Ai,2, ,…,Ai,Ki} consisting of Ki vertices. For every pair u,v such that u,v ∈ Si and u<v, add an edge between vertices u and v with weight Ci.
After performing all M operations, determine whether G is connected. If it is, find the total weight of the edges in a minimum spanning tree of G.
Code:
The code runs okay. Ideone
from collections import defaultdict
from heapq import heappush, heappop
def solution(A):
def prim(G):
vis = set()
start = next(iter(G))
vis.add(start)
Q, mst = [], []
for w, nei in G[start]:
heappush(Q, (w, start, nei))
while len(vis) < len(G):
w, src, dest = heappop(Q)
if dest in vis:
continue
vis.add(dest)
mst.append((src, dest, w))
for w, nei in G[dest]:
heappush(Q, (w, dest, nei))
return mst
N, M = A[0]
graph = defaultdict(list)
for i in range(1, len(A)):
if i % 2 == 1:
k, c = A[i]
else:
edges = A[i]
for ii in range(len(edges)):
for jj in range(ii + 1, len(edges)):
if edges[ii] < edges[jj]:
graph[edges[jj]].append((c, edges[ii]))
graph[edges[ii]].append((c, edges[jj]))
mst = prim(graph)
res = 0
s = set()
for x, y, w in mst:
res += w
s.update({x, y})
if sorted(s) != list(range(1, N + 1)):
print(-1)
else:
print(res)
A = [[10, 5], [6, 158260522], [1, 3, 6, 8, 9, 10], [10, 877914575], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[4, 602436426], [2, 6, 7, 9], [6, 24979445], [2, 3, 4, 5, 8, 10], [4, 861648772], [2, 4, 8, 9]]
solution(A)
Question
- How do we optimize it so that we won't get TLE? The running time must be below 2 seconds.