[백준] 10825. 국영수
문제 링크
풀이 과정
정렬 문제입니다.
다음은 Stream을 이용한 풀이입니다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = stoi(br.readLine());
List<Student> list = new ArrayList<>();
while (N-- > 0) {
StringTokenizer st = new StringTokenizer(br.readLine());
list.add(new Student(st.nextToken(), stoi(st.nextToken()), stoi(st.nextToken()), stoi(st.nextToken())));
}
list.stream()
.sorted(Comparator.comparing(Student::getKo).reversed()
.thenComparing(Student::getEn)
.thenComparing(Comparator.comparing(Student::getMath).reversed())
.thenComparing(Student::getName))
.map(Student::getName)
.forEach(System.out::println);
}
static class Student {
String name;
int ko, en, math;
public Student(String name, int ko, int en, int math) {
this.name = name;
this.ko = ko;
this.en = en;
this.math = math;
}
public int getKo() { return ko; }
public int getEn() { return en; }
public int getMath() { return math; }
public String getName() { return name; }
}
public static int stoi(String s) { return Integer.parseInt(s); }
}
@Override
public int compareTo(Student o) {
if (this.korean == o.korean) {
if (this.english == o.english) {
if (this.math == o.math) {
return name.compareTo(o.name);
} else {
return Integer.compare(o.math, this.math);
}
} else {
return Integer.compare(this.english, o.english);
}
} else {
return Integer.compare(o.korean, this.korean);
}
}
문제의 정렬 규칙에 맞게 위와 같이 compareTo 메서드
를 작성할 수 있습니다.
코드
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
ArrayList<Student> list = new ArrayList<>();
for (int i = 0; i < N; i++) list.add(new Student(sc.next(), sc.nextInt(), sc.nextInt(), sc.nextInt()));
Collections.sort(list);
StringBuilder sb = new StringBuilder();
for (Student student : list) {
sb.append(student.name);
sb.append("\n");
}
System.out.println(sb);
}
static class Student implements Comparable<Student> {
String name;
int korean, english, math;
public Student(String name, int korean, int english, int math) {
this.name = name;
this.korean = korean;
this.english = english;
this.math = math;
}
@Override
public int compareTo(Student o) {
if (this.korean == o.korean) {
if (this.english == o.english) {
if (this.math == o.math) {
return name.compareTo(o.name);
} else {
return Integer.compare(o.math, this.math);
}
} else {
return Integer.compare(this.english, o.english);
}
} else {
return Integer.compare(o.korean, this.korean);
}
}
}
}
댓글남기기