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.
publicstaticlongroadsAndLibraries(intn,intc_lib,intc_road,List<List<Integer>>cities){if(cities.isEmpty()||c_lib<=c_road)return1L*n*c_lib;TreeMap<Integer,Stack<Integer>>cityMap=newTreeMap<>();for(List<Integer>connection:cities){intc1=connection.get(0),c2=connection.get(1);cityMap.computeIfAbsent(c1,k->newStack<>()).add(c2);cityMap.computeIfAbsent(c2,k->newStack<>()).add(c1);}longlibs=n-cityMap.size(),roads=0L;while(!cityMap.isEmpty()){// Start new cyclelibs++;Stack<Integer>stack=cityMap.pollFirstEntry().getValue();while(!stack.isEmpty()){// DFS for connected citiesintc=stack.pop();if(cityMap.containsKey(c)){roads++;stack.addAll(cityMap.remove(c));}}}returnlibs*c_lib+roads*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 →
Solution in Java, quick and simple