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.
//package solve_problems;/* * 2024 ^_^ * * */importjava.math.BigInteger;importjava.util.ArrayList;importjava.util.Arrays;importjava.util.Collections;importjava.util.Comparator;importjava.util.HashMap;importjava.util.Set;importjava.util.HashSet;importjava.util.List;importjava.util.Map;importjava.util.Scanner;publicclassSolve_problems{staticclassPairimplementsComparable<Pair>{intfirst;intsecond;publicPair(inta,intb){this.first=a;this.second=b;}@OverridepublicintcompareTo(Pairt){returnInteger.compare(this.first,t.first);}}staticintsolve(List<Integer>arr){List<Pair>parr1=newArrayList<>(arr.size());List<Pair>parr2=newArrayList<>(arr.size());for(inti=0;i<arr.size();i++){parr1.add(newPair(arr.get(i),i));parr2.add(newPair(arr.get(i),i));}// Example: Print contents of parr1// parr1.forEach(item -> {// System.out.println(item.first + " " + item.second);// });Collections.sort(parr1);Collections.sort(parr2,Collections.reverseOrder());//reverse theo firstintcounta=0;intcountd=0;//sort second tang dan nhung van giu nguyen thu tu first//This algorithm effectively sorts the list based on the second component of each pair.for(inti=0;i<parr1.size();i++){while(i!=parr1.get(i).second){inttemp=parr1.get(i).second;parr1.get(i).second=parr1.get(temp).second;parr1.get(temp).second=temp;counta++;}}for(inti=0;i<parr2.size();i++){while(i!=parr2.get(i).second){inttemp=parr2.get(i).second;parr2.get(i).second=parr2.get(temp).second;parr2.get(temp).second=temp;countd++;}}returnMath.min(counta,countd);}publicstaticvoidmain(String[]args){Scannersc=newScanner(System.in);/////////////// intn=sc.nextInt();List<Integer>arr=newArrayList<>();for(inti=0;i<n;i++)arr.add(sc.nextInt());System.out.println(solve(arr));/////////////////sc.close();}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Lily's Homework
You are viewing a single comment's thread. Return to all comments →