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.
classResult{publicstaticlongjourneyToMoon(intn,List<List<Integer>>astronaut){List<List<Integer>>adjList=newArrayList<>();for(inti=0;i<n;i++){adjList.add(newArrayList<>());}for(List<Integer>pair:astronaut){intu=pair.get(0);intv=pair.get(1);adjList.get(u).add(v);adjList.get(v).add(u);}boolean[]visited=newboolean[n];List<Integer>countrySizes=newArrayList<>();for(inti=0;i<n;i++){if(!visited[i]){intcountrySize=dfs(i,adjList,visited);countrySizes.add(countrySize);}}longtotalPairs=(long)n*(n-1)/2;longsameCountryPairs=0;for(intsize:countrySizes){sameCountryPairs+=(long)size*(size-1)/2;}returntotalPairs-sameCountryPairs;}privatestaticintdfs(intnode,List<List<Integer>>adjList,boolean[]visited){Stack<Integer>stack=newStack<>();stack.push(node);visited[node]=true;intsize=0;while(!stack.isEmpty()){intcurrent=stack.pop();size++;for(intneighbor:adjList.get(current)){if(!visited[neighbor]){visited[neighbor]=true;stack.push(neighbor);}}}returnsize;}}publicclassSolution{publicstaticvoidmain(String[]args)throwsIOException{BufferedReaderbufferedReader=newBufferedReader(newInputStreamReader(System.in));BufferedWriterbufferedWriter=newBufferedWriter(newFileWriter(System.getenv("OUTPUT_PATH")));String[]firstMultipleInput=bufferedReader.readLine().replaceAll("\\s+$","").split(" ");intn=Integer.parseInt(firstMultipleInput[0]);intp=Integer.parseInt(firstMultipleInput[1]);List<List<Integer>>astronaut=newArrayList<>();IntStream.range(0,p).forEach(i->{try{astronaut.add(Stream.of(bufferedReader.readLine().replaceAll("\\s+$","").split(" ")).map(Integer::parseInt).collect(toList()));}catch(IOExceptionex){thrownewRuntimeException(ex);}});longresult=Result.journeyToMoon(n,astronaut);// Change int to longbufferedWriter.write(String.valueOf(result));bufferedWriter.newLine();bufferedReader.close();bufferedWriter.close();}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Journey to the Moon
You are viewing a single comment's thread. Return to all comments →
Java O(n+p)