ALGORITHM

[JAVA] 백준 10825번- 국영수

연듀 2022. 7. 30. 17:33

https://www.acmicpc.net/problem/10825

 

10825번: 국영수

첫째 줄에 도현이네 반의 학생의 수 N (1 ≤ N ≤ 100,000)이 주어진다. 둘째 줄부터 한 줄에 하나씩 각 학생의 이름, 국어, 영어, 수학 점수가 공백으로 구분해 주어진다. 점수는 1보다 크거나 같고, 1

www.acmicpc.net

 

 

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