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.
fromcollectionsimportdefaultdict,dequedefroadsAndLibraries(n,c_lib,c_road,cities):"""Cost1:onelibineachcityFormula:c_lib*nCost2:onelibpergroupofconnectedcities+connectingroadsFormula:c_lib*k+c_road*(n-k),wherekisnumberofgroupsIfc_lib<=c_road,Cost1islower;otherwise,Cost2is."""# Return Cost 1ifc_lib<=c_road:returnc_lib*n# Calculate Cost 2 below:# Initialize number of groupsk=0# Record direct connections for each cityconnections=defaultdict(set)fora,bincities:connections[a].add(b)connections[b].add(a)# Track visited citiesvisited=[False]*(n+1)# Identify connected components (groups of cities)forcityinrange(1,n+1):ifvisited[city]:continue# Start a new groupvisited[city]=Truek+=1# BFS to mark all cities in this groupdq=deque([city])whiledq:curr_city=dq.popleft()forlinked_cityinconnections[curr_city]:ifnotvisited[linked_city]:visited[linked_city]=Truedq.append(linked_city)# Return Cost 2returnc_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 →