We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
defroadsAndLibraries(n,c_lib,c_road,cities):# If library cost is less than or equal to road cost, build a library in each cityifc_lib<=c_road:returnc_lib*n# Initialize disjoint set (union-find) structuresroot=list(range(n+1))rank=[0]*(n+1)deffind_root(i):ifroot[i]!=i:root[i]=find_root(root[i])#Pathcompressionreturnroot[i]defunion(a,b):i,j=find_root(a),find_root(b)ifi!=j:# Union by rankifrank[i]>rank[j]:root[j]=ielifrank[i]<rank[j]:root[i]=jelse:root[j]=irank[i]+=1# Union all connected citiesfora,bincities:union(a,b)# Count connected componentsk=sum(1forcityinrange(1,n+1)ifroot[city]==city)# Calculate total cost: one library per component + roads for remaining citiesreturnc_lib*k+c_road*(n-k)
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Roads and Libraries
You are viewing a single comment's thread. Return to all comments →