1. 문제
10825번: 국영수
첫째 줄에 도현이네 반의 학생의 수 N (1 ≤ N ≤ 100,000)이 주어진다. 둘째 줄부터 한 줄에 하나씩 각 학생의 이름, 국어, 영어, 수학 점수가 공백으로 구분해 주어진다. 점수는 1보다 크거나 같고, 1
www.acmicpc.net
도현이네 반 학생 N명의 이름과 국어, 영어, 수학 점수가 주어진다. 이때, 다음과 같은 조건으로 학생의 성적을 정렬하는 프로그램을 작성하시오.
1. 국어 점수가 감소하는 순서로
2. 국어 점수가 같으면 영어 점수가 증가하는 순서로
3. 국어 점수와 영어 점수가 같으면 수학 점수가 감소하는 순서로
4. 모든 점수가 같으면 이름이 사전 순으로 증가하는 순서로 (단, 아스키 코드에서 대문자는 소문자보다 작으므로 사전순으로 앞에 온다.)
2. 풀이
Student 클래스
1. 빠른 비교를 위해 Student클래스를 만들었다. Comparable를 상속받아서 compareTo 함수를 오버라이딩한다.
2. 국어점수가 다르다면 국어점수 내림차순, 영어점수가 다르다면 영어점수 오름차순, 수학점수가 다르다면 수학점수 내림차순, 점수가 모두 같다면 이름 오름차순으로 정렬한다.
3. 기본 생성자는 모두 String을 받아서 생성자 안에서 int로 변경했다.
private static class Student implements Comparable<Student> {
String name;
int korean,math,english;
Student(String name, String korean, String english, String math){
this.name = name;
this.korean = Integer.parseInt(korean);
this.math = Integer.parseInt(math);
this.english = Integer.parseInt(english);
}
@Override
public int compareTo(Student o) {
if(this.korean != o.korean) return o.korean-this.korean;
else if(this.english != o.english) return this.english - o.english;
else if(this.math != o.math) return o.math - this.math;
else return this.name.compareTo(o.name);
}
}
메인
1. students 배열에 입력을 받는다. 이 때 바로 int로 변경하지 않고 StringTokenizer로 쪼갠 String을 바로 생성자에 넣었다.
2. Arrays.sort로 정렬한다. 정렬된 결과를 StringBuilder에 모아서 출력한다.
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(in.readLine());
Student[] students = new Student[N];
StringTokenizer st;
for(int i=0;i<N;i++){
st = new StringTokenizer(in.readLine());
students[i] = new Student(st.nextToken(),st.nextToken(),st.nextToken(),st.nextToken());
}
Arrays.sort(students);
StringBuilder sb = new StringBuilder();
for(int i=0;i<N;i++){
sb.append(students[i].name).append('\n');
}
System.out.print(sb);
}
3. 결과
'코딩테스트 > BOJ' 카테고리의 다른 글
[BOJ] 2869 달팽이는 올라가고 싶다 - JAVA (0) | 2022.07.05 |
---|---|
[BOJ] 2504 괄호의 값 - JAVA (0) | 2022.07.04 |
[BOJ] 2003 수들의 합 2 - JAVA (0) | 2022.07.02 |
[BOJ] 1251 단어 나누기 - JAVA (0) | 2022.07.01 |
[BOJ] 2217 로프 - JAVA (0) | 2022.06.30 |
댓글