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.
The key is to recognize the following. If c_lib <= c_road, then we just build libraries at each city. Otherwise, you should always build a road if the road connects distinct components of the cities. Therefore, we should return c_lib*(the number of the components of the cities) + c_road*(n - the number of the components of the cities). Hence, the problem is a standard question to count the number of components of a given graph.
fromcollectionsimportdefaultdict,dequedefroadsAndLibraries(n,c_lib,c_road,cities):# Write your code hereifc_lib<=c_road:returnn*c_libnbd=defaultdict(set)fore1,e2incities:nbd[e1].add(e2)nbd[e2].add(e1)seen=set()defget_component(start):comp=deque([start])seen.add(start)whilecomp:node=comp.popleft()fornext_nodeinnbd[node]:ifnext_nodenotinseen:comp.append(next_node)seen.add(next_node)final_comp_num=0foriinrange(1,n+1):ifinotinseen:get_component(i)final_comp_num+=1returnc_lib*final_comp_num+c_road*(n-final_comp_num)
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 →
The key is to recognize the following. If c_lib <= c_road, then we just build libraries at each city. Otherwise, you should always build a road if the road connects distinct components of the cities. Therefore, we should return c_lib*(the number of the components of the cities) + c_road*(n - the number of the components of the cities). Hence, the problem is a standard question to count the number of components of a given graph.