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.
library(igraph)roadsAndLibraries<-function(N,c_lib,c_road,cities){# https://stackoverflow.com/questions/6042728/nas-produced-by-integer-overflow-r-on-linuxN<-as.numeric(N)c_lib<-as.numeric(c_lib)c_road<-as.numeric(c_road)# if libraries are cheaper than roads, just build thoseif(c_lib<=c_road){return(N*c_lib)}# the isolated city count:# the number of cities (N) not present in edges (cities)isolated_cities<-N-length(unique(as.vector(cities)))# this exercise treats numbers as names; igraph treats numbers as numbers# so redefine cities as stringsclass(cities)<-"character"# use igraph to get city clusterscity_clusters<-components(graph_from_edgelist(cities,directed=FALSE))# each cluster and isolated city will require 1 libraryresult<-c_lib*(city_clusters$no+isolated_cities)+# each city without a library requires a roadsum(c_road*# so for each cluster, that's its size minus 1(city_clusters$csize-1))return(result)}
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 →
R with inline comments