문제에 대한 자세한 정보는 백준 | 10825번 : 국영수에서 확인할 수 있다.
풀이
- 이름, 국어 점수, 영어 점수, 수학 점수를 객체 변수로 가지는 Student class를 작성한다.
- 정렬을 위한 Arrays.sort() 사용을 위해 주어진 정렬 조건에 따라 compareTo(Student o) 메소드를 작성한다.
- 첫째 줄에 입력받은 학생의 수 N 길이를 가지는 Student 객체 배열을 생성한다.
- 학생의 이름, 성적을 입력받아 배열에 저장한다.
- Arrays.sort()를 사용해 정렬하고 출력한다.
소스코드
import java.io.*;
import java.util.*;
class Student implements Comparable<Student> {
String name;
int kor, eng, math;
public Student(String name, int kor, int eng, int math) {
this.name = name;
this.kor = kor;
this.eng = eng;
this.math = math;
}
@Override
public int compareTo(Student o) {
if (this.kor == o.kor) {
if (this.eng == o.eng) {
if (this.math == o.math) {
return this.name.compareTo(o.name);
}
return o.math - this.math;
}
return this.eng - o.eng;
}
return o.kor - this.kor;
}
@Override
public String toString() {
return this.name + "\n";
}
}
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int N = Integer.valueOf(br.readLine());
Student[] student = new Student[N];
for (int i = 0; i < N; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
String name = st.nextToken();
int kor = Integer.valueOf(st.nextToken());
int eng = Integer.valueOf(st.nextToken());
int math = Integer.valueOf(st.nextToken());
student[i] = new Student(name, kor, eng, math);
}
Arrays.sort(student);
for (int i = 0; i < N; i++) {
bw.write(student[i].toString());
}
br.close();
bw.close();
}
}
메모리, 시간
메모리 : 68656KB
시간 : 708ms
풀이 후
compareTo(Student o) 메소드만 잘 작성하면 크게 어려운 문제는 아니었다.
그런데 문제의 조건 중
모든 점수가 같으면 이름이 사전 순으로 증가하는 순서
이 조건을 이름 맨 앞 글자만 비교하면 되겠다라고 착각했다. 바보같다.
조금 더 꼼꼼히 생각하는 습관을 길러야겠다.
'알고리즘 > 백준' 카테고리의 다른 글
| 백준 | 10814 : 나이순 정렬 (Java) (0) | 2022.08.19 |
|---|---|
| 백준 | 11651 : 좌표 정렬하기 2 (Java) (0) | 2022.08.15 |
| 백준 | 2751 : 수 정렬하기 2 (Java) (0) | 2022.08.15 |
| 백준 | 11650 : 좌표 정렬하기 (Java) (0) | 2022.08.15 |