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.
defroadsAndLibraries2(n,c_lib,c_road,cities):# cost 1: c_lib * nifc_lib<=c_road:returnc_lib*n# cost 2: c_lib * k + c_road * (n - k), where k is num of connected components# Initialize parent array for disjoint-set data structureparent=list(range(n+1))# Initialize rank array for union by rank optimizationrank=[0]*(n+1)# Find operation to recursively find the representative of a setdeffind_parent(city):ifparent[city]==city:returncity# Path compression: update parent pointers to point directly to the rootparent[city]=find_parent(parent[city])returnparent[city]# Union operation to merge two setsdefunion(city1,city2):a,b=find_parent(city1),find_parent(city2)ifa==b:return# Union by rank: merge smaller tree into larger treeifrank[a]>rank[b]:parent[b]=aelifrank[a]<rank[b]:parent[a]=belse:parent[b]=arank[a]+=1# Merge sets based on given roadsforcity1,city2incities:union(city1,city2)# Count the number of connected components (sets with representatives)k=sum(1forcityinrange(1,n+1)ifparent[city]==city)# Calculate cost based on the number of connected componentsreturnc_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 →