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.
Java8, int return fails at test case 11; changing to long fixes it
classDisjointSet{privateint[]nations;privateint[]count;intn;publicDisjointSet(intn){nations=newint[n];count=newint[n];this.n=n;for(inti=0;i<n;i++){nations[i]=i;count[i]=1;}}publicintfind(inti){if(i!=nations[i]){nations[i]=find(nations[i]);}returnnations[i];}publicvoidunion(intx,inty){x=find(x);y=find(y);if(x==y){return;}if(count[x]<=count[y]){nations[x]=y;count[y]+=count[x];}else{nations[y]=x;count[x]+=count[y];}}publicTreeMap<Integer,Integer>getNationMap(){TreeMap<Integer,Integer>res=newTreeMap<>();for(inti=0;i<n;i++){intnewI=find(i);res.put(newI,count[newI]);}returnres;}}classResult{publicstaticlongjourneyToMoon(intn,List<List<Integer>>astronaut){// Write your code hereDisjointSetset=newDisjointSet(n);for(List<Integer>list:astronaut){intx=list.get(0);inty=list.get(1);set.union(x,y);}TreeMap<Integer,Integer>nationMap=set.getNationMap();longallPairsIncludingSameNation=((long)n*(long)(n-1))/2;longpairsSameNation=0;for(Map.Entry<Integer,Integer>e:nationMap.entrySet()){longcount=e.getValue();longpairs=(count*(count-1))/2;pairsSameNation+=pairs;}returnallPairsIncludingSameNation-pairsSameNation;}}
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 →
Java8, int return fails at test case 11; changing to long fixes it