국영수 - 10825

Seongjin Jo·2023년 5월 17일
0

Baekjoon

목록 보기
28/51

문제

풀이

import java.util.*;

// 국영수 - 정렬
class Sum implements Comparable<Sum>{
    String name;
    int a; //국어
    int b; //영어
    int c; //수학

    public Sum(String name, int a, int b, int c) {
        this.name = name;
        this.a = a;
        this.b = b;
        this.c = c;
    }

    @Override
    public int compareTo(Sum o) {
        if(this.a == o.a) {
            if(this.b == o.b){
                if(this.c == o.c){
                    return this.name.compareTo(o.name);
                }
                return o.c - this.c;
            }
            return this.b - o.b;
        }
        return o.a - this.a;
    }
}
public class ex10825 {
    static int n;
    static ArrayList<Sum> list = new ArrayList<>();

    public static ArrayList<Sum> solution(){
        Collections.sort(list);
        return list;
    }

    public static void main(String[] args) {
        Scanner sc =new Scanner(System.in);

        n = sc.nextInt();


        for(int i=0; i<n; i++){
            String name = sc.next();
            int a = sc.nextInt();
            int b = sc.nextInt();
            int c =  sc.nextInt();

            list.add(new Sum(name,a,b,c));
        }

        for(Sum x : solution()){
            System.out.println(x.name);
        }
    }

}

매우매우매우매우 중요한 문제다. Comparable , Comparator 인터페이스를 이용한 정렬의 핵심 문제.

문제 설명

국어 내림차순
국어 같으면 영어 오름차순
국어,영어 같으면 수학 내림차순
모든 점수 같으면 이름 오름차순

이름 국어 영어 수학 순으로 입력

이렇게 정렬하면 된다.

근데 처음엔 Comparable 정렬함수를 이런식으로 정렬하려고 시도했다.

if() return 국어같으면 영어 오름차순
else if() return 국어,영어 같으면 수학 내림차순
else if() return 이름 오름차순 --> return 타입 안맞아서 안됨.
return 국어 내림차순

입력 후에 출력값을 대충 봤는데 제대로 정렬이 안되는 걸 확인했다. 그래서 여러가지 조건을 하기 위해서는 무조건 한 if문안에 다 엮어야 한다.

if(){
	if(){
    	if(){
        	return ~~~
        }
    }
}
return 정렬

이런 구조로 정렬을 다 엮어야 한다.

그리고 name은 반환타입이 String이라서 그냥 return하면 안되더라. 그래서 확인해보니까

return this.name.compareTo(o.name); //오름차순
return o.name.compareTo(this.name); //내림차순

이런 식으로 정렬하면 String 타입 name도 정렬이 가능하다. 핵심 !! 꼭 외우자.

0개의 댓글