알고리즘/백준

10825 - 국영수[S4]

블랑v 2023. 12. 8. 13:11

 

문제

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

 

10825번: 국영수

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

www.acmicpc.net

 

도현이네 반 학생 N명의 이름과 국어, 영어, 수학 점수가 주어진다. 이때, 다음과 같은 조건으로 학생의 성적을 정렬하는 프로그램을 작성하시오.

  1. 국어 점수가 감소하는 순서로
  2. 국어 점수가 같으면 영어 점수가 증가하는 순서로
  3. 국어 점수와 영어 점수가 같으면 수학 점수가 감소하는 순서로
  4. 모든 점수가 같으면 이름이 사전 순으로 증가하는 순서로 (단, 아스키 코드에서 대문자는 소문자보다 작으므로 사전순으로 앞에 온다.)

풀이

조건에 따른 정렬을 수행하는 문제이다.

연습용으로 Comparator 역시 구현해보았다. (자세한 로직은 생략)

이 문제에서 눈여겨볼 점은 compareTo를 통한 String 비교 구문이다. 모른다면 틀렸을 것 같다.

 

코드

 

import java.util.*;
import java.io.*;
class Main {
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
    static int N;
    public static void main(String[] args) throws Exception {
    	N = Integer.parseInt(br.readLine());
    	

    
    	//1. Comparator 사용
    	PriorityQueue<StudentNotComparable> pq = new PriorityQueue<>(
    			new Comparator<>() {
					@Override
					public int compare(StudentNotComparable o1, StudentNotComparable o2) {
						//내부 구문 생략 .. Student Class의 compareTo 참고할 것.
						return 0;
					}
    			}
    			);
    	
    	//2. Comparable 사용
    	Student arr[] = new Student[N];
    	
    	
    	for(int i = 0; i < N; i++) {
    		StringTokenizer 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());
    		
    		//1. PQ용
    		pq.offer(new StudentNotComparable(name, kor, eng, math));
    		
    		//2. Comparable용
    		arr[i] = new Student(name, kor, eng, math); //이후 sort
    	}
    	Arrays.sort(arr);
    	
    	for(int i = 0; i < N; i++) {
    		System.out.println(arr[i].name);
    	}
    	
    } //EOM
} //EOC

class Student implements Comparable<Student> {
	String name;
	int kor, eng, math;
	
	@Override
	public int compareTo(Student s) {
		if(this.kor == s.kor) {
			if(this.eng == s.eng) {
				if(this.math == s.math) {
					return this.name.compareTo(s.name); //String의 경우 compareTo 사용
				}
				return s.math - this.math;
			}
			return this.eng - s.eng;
		}
		return s.kor - this.kor;
	}
	
	public Student(String name, int kor, int eng, int math) {
		this.name = name;
		this.kor = kor;
		this.eng = eng;
		this.math = math;
	}
}

//Comparable 사용하지 않음
class StudentNotComparable {
	String name;
	int kor, eng, math;
	public StudentNotComparable(String name, int kor, int eng, int math) {
		this.name = name;
		this.kor = kor;
		this.eng = eng;
		this.math = math;
	}
}