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):# Write your code hereifc_lib<=c_road:returnn*c_lib# adjacency listprint(cities)city_list=[[]forjinrange(n)]forkinrange(len(cities)):start=cities[k][0]end=cities[k][1]city_list[start-1].append(end-1)city_list[end-1].append(start-1)# num of connected components (DFS)reached=[0]*ncomponents=0defDFS(x):reached[x]=1foryincity_list[x]:ifreached[y]==0:DFS(y)forxinrange(n):ifreached[x]==0:DFS(x)components+=1# calculate resultreturncomponents*c_lib+(n-components)*c_road
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 →
Answer in Python