우보천리 개발

[BJ] 10825 국영수 Java 본문

알고리즘/백준

[BJ] 10825 국영수 Java

밥은답 2023. 2. 1. 23:41
반응형

백준 10825 국영수

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

 

10825번: 국영수

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

www.acmicpc.net

아이디어

  • Comparator 을 재정의해서 문제에서 요구하는 기준으로 정렬을 하면 되는 문제이다

코드

import java.io.*;
import java.util.*;

class BJ10825 {
	// 문제에서 요구하는 점수와 이름을 저장하는 클래스를 정의하는데
    // 정렬 기준을 정의해야하기 때문에 Comparable 클래스 구현
    static class Score implements Comparable<Score>{
        int lang, eng, math;
        String name;
        public Score(String name, int lang, int eng, int math) {
            this.lang = lang;
            this.eng = eng;
            this.math = math;
            this.name = name;
        }
        @Override
        // 오름차순인 경우 클래스의 객체에서 매개변수로 들어오는 객체를 뺀다
        public int compareTo(Score other) {
            if (this.lang == other.lang) {
                if (this.eng == other.eng) {
                    if (this.math == other.math) {
                    	// 문자열의 경우 compareTo 사용
                        return this.name.compareTo(other.name);
                    }
                    return other.math - this.math;
                }
                return this.eng - other.eng;
            }
            return other.lang - this.lang;
        }
    }

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        ArrayList<Score> al = new ArrayList<>();
        StringTokenizer st;
        for (int i=0; i<n; i++) {
            st = new StringTokenizer(br.readLine());
            String name = st.nextToken();
            int lang = Integer.parseInt(st.nextToken());
            int eng = Integer.parseInt(st.nextToken());
            int math = Integer.parseInt(st.nextToken());
            al.add(new Score(name, lang, eng, math));
        }

		// 기준을 재정의했기 때문에 기준에 맞게 다시 정렬
        Collections.sort(al);
        
        for (Score s : al) {
            System.out.println(s.name);
        }
    }
}
반응형

'알고리즘 > 백준' 카테고리의 다른 글

[BJ] 1715 카드 정렬하기  (0) 2023.02.02
[BJ] 18310 안테나 Java  (0) 2023.02.01
[BJ] 18428 감시 피하기 Java  (0) 2023.01.31
[BJ] 14888 연산자 끼워넣기 Java  (0) 2023.01.30
[BJ] 14502 연구소 Java  (0) 2023.01.30
Comments