https://www.acmicpc.net/problem/10825
import java.util.*;
class Student implements Comparable<Student> {
String name;
int korean, math, english;
public Student(String name, int korean, int english, int math){
this.name = name;
this.korean = korean;
this.math = math;
this.english = english;
}
@Override
public int compareTo(Student s) {
if(this.korean == s.korean) { // 국어가 같으면
if(this.english == s.english){ // 영어 점수가 같으면
if(this.math == s.math){ // 수학 점수가 같으면
return this.name.compareTo(s.name);// 이름이 사전 순으로 증가하는 순으로
}
return s.math - this.math; // 수학 점수는 내림차순으로
}
return this.english - s.english;// 영어 점수는 오름차순으로
}
return s.korean - this.korean; // 국어는 내림차순으로
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
ArrayList<Student> arr = new ArrayList<>();
String name;
int korean, math, english;
for(int i=0; i<n; i++){
name = sc.next();
korean = sc.nextInt();
english = sc.nextInt();
math = sc.nextInt();
arr.add(new Student(name, korean, english, math));
}
Collections.sort(arr);
for(Student s: arr) System.out.println(s.name);
}
}
이전에 풀었던 20920번 문제와 비슷한 문제였다.
자기자신과 파라미터로 들어오는 객체를 비교하는 Comparable 인터페이스를 사용하였다.
this 객체가 앞에 있고, 매개변수로 받은 객체가 뒤에 있다고 하자.
이 순서대로 정렬이 되려면 무조건 음수 값이 리턴되면 된다.
예를 들어 this가 10, 매개변수가 20이라고 할 때 this에서 매개변수를 빼면 음수가 되어 오름차순이 된다.
반대로 내림차순으로 정렬하고 싶다면 매개변수에서 this를 빼어 음수로 만들면 된다.
compareTo 메소드는 기준값이 비교하는 값보다 사전 순으로 더 뒤에 있으면 1을 반환하고, 반대면 -1을 반환한다.
comparable/comparator 참고
https://st-lab.tistory.com/243
'ALGORITHM' 카테고리의 다른 글
[JAVA] 백준 2941번- 크로아티아 알파벳 (0) | 2022.08.01 |
---|---|
[JAVA] 백준 5622번- 다이얼 (0) | 2022.08.01 |
[JAVA] 백준 10815번- 숫자 카드 (0) | 2022.07.30 |
[JAVA] 백준 1920번- 수 찾기 (0) | 2022.07.30 |
[JAVA] 알고리즘 : 정렬- 뮤직비디오(결정 알고리즘) (0) | 2022.07.28 |