728x90
10825번: 국영수
첫째 줄에 도현이네 반의 학생의 수 N (1 ≤ N ≤ 100,000)이 주어진다. 둘째 줄부터 한 줄에 하나씩 각 학생의 이름, 국어, 영어, 수학 점수가 공백으로 구분해 주어진다. 점수는 1보다 크거나 같고, 1
www.acmicpc.net
단순히 이중 for문으로 해결하면 시간초과 뜨는 문제다. 그리디 알고리즘 할 때 배웠던 Comparable
인터페이스를 이용해 해결하였다. Comparable
에서 compareTo
는 정렬하는 기준을 잡아주는 메서드이다.
public int compareTo(Grade o) {
/* 국어 점수기준으로 내림차순 정렬. 값이 같다면 영어점수 기준으로
* 오름차순 같다면 수학점수 기준으로 내림차순. 마지막 이름 사전식 정렬 */
if (this.kor == o.kor) {
if (this.eng == o.eng) {
if (this.math == o.math) {
// 문자열의 사전순으로 비교 후 오름차순 정렬
return this.name.compareTo(o.name);
} else {
return o.math - this.math;
}
} else {
return this.eng - o.eng;
}
} else {
return o.kor - this.kor;
}
}
💻 실행코드
import java.io.*;
import java.util.*;
class Grade implements Comparable<Grade> {
String name;
int kor;
int eng;
int math;
public Grade(String name, int kor, int eng, int math) {
this.name = name;
this.kor = kor;
this.eng = eng;
this.math = math;
}
@Override
public int compareTo(Grade o) {
if (this.kor == o.kor) {
if (this.eng == o.eng) {
if (this.math == o.math) {
return this.name.compareTo(o.name);
} else {
return o.math - this.math;
}
} else {
return this.eng - o.eng;
}
} else {
return o.kor - this.kor;
}
}
}
class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st;
int n = Integer.parseInt(br.readLine());
List<Grade> list = new ArrayList<>();
int num = 1;
for (int i = 0; i < n; i++) {
st = new StringTokenizer(br.readLine());
String name = st.nextToken();
int kor = Integer.parseInt(st.nextToken());
int eng = Integer.parseInt(st.nextToken());
int math = Integer.parseInt(st.nextToken());
Grade grade = new Grade(name, kor, eng, math);
list.add(grade);
}
Collections.sort(list);
for (Grade g : list) {
System.out.println(g.name);
}
}
}
728x90
'Algorithm > Problem Solving' 카테고리의 다른 글
[BOJ] 2110번 공유기 설치 - JAVA(자바) (0) | 2023.09.14 |
---|---|
[BOJ] 1654번 랜선 자르기 - JAVA(자바) (0) | 2023.09.12 |
[BOJ] 2805번 나무 자르기 - JAVA(자바) (0) | 2023.09.12 |
[BOJ] 1002번 터렛 - JAVA(자바) (0) | 2023.08.03 |
[BOJ] 2960번 에라토스테네스의 체 - JAVA(자바) (0) | 2023.08.03 |