반응형
문제
https://www.acmicpc.net/problem/7568
코드
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
Person[] people = new Person[N];
for (int i = 0; i < N; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
Person person = new Person(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()));
people[i] = person;
}
StringBuilder sb = new StringBuilder();
for (Person person1 : people) {
int rank = 1;
for (Person person2 : people) {
if (person2.compareTo(person1) > 0) {
rank++;
}
}
sb.append(rank).append(" ");
}
System.out.println(sb);
}
private static class Person implements Comparable<Person> {
private final int weight;
private final int height;
private Person(int weight, int height) {
this.weight = weight;
this.height = height;
}
@Override
public int compareTo(Person o) {
if (this.weight > o.weight && this.height > o.height) {
return 1;
}
return 0;
}
}
}
풀이
이번 문제에서는 두 가지 기준으로 사람을 비교해야 한다. 그래서 그냥 바로 Person 클래스에 `Comparable<Person>` 인터페이스를 구현하여, `compareTo()` 메서드 안에서 키와 몸무게를 동시에 비교하는 로직을 정의했다. 이렇게 하고 `Arrays.sort(people)`을 하면 한 번에 정렬될 수 있어서 편하기 때문이다.
import java.io.*;
import java.util.*;
public class bj_7568 {
public void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
Person[] people = new Person[N];
for (int i = 0; i < N; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
Person person = new Person(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()));
people[i] = person;
}
Arrays.sort(people);
}
private class Person implements Comparable<Person> {
private final int weight;
private final int height;
private Person(int weight, int height) {
this.weight = weight;
this.height = height;
}
@Override
public int compareTo(Person o) {
if (this.weight > o.weight && this.height > o.height) {
return 1;
}
return 0;
}
}
}
그리고 이제 입력된 사람의 순서에 맞추어서 등수를 출력하자! → 근데 어떻게 하지...? `compareTo`에서 몸무게와 키 모두 클 경우가 아니면 `0(같다)`로 인식하라고 했는데 그건 `people` 리스트에서 어떻게 알지...? 이 생각이 들었다.
계속 고민하다가 알고리즘 분류를 보니깐 적혀있는 브루트포스.... 너무 복잡하게 생각하고 풀었다......ㅎㅎ
그래서 그냥 `sort`하는 부분을 제거하고 이중 `for`문에서 `compareTo` 메서드를 통해 비교하면서 `rank`를 `1`씩 더해주었다.
for (Person person1 : people) {
int rank = 1; // 기본 등수는 1등부터 시작
for (Person person2 : people) {
if (person2.compareTo(person1) > 0) {
// person2가 person1보다 몸무게·키 모두 크면 person1의 등수를 1 올림
rank++;
}
}
sb.append(rank).append(" ");
}
반응형
'백준' 카테고리의 다른 글
[백준] 15829: Hashing (0) | 2025.04.22 |
---|---|
[백준] 2667: 단지번호붙이기 (0) | 2025.04.21 |
[백준] 4949: 균형잡힌 세상 (0) | 2025.04.18 |
[백준] 2275: 부녀회장이 될테야 (0) | 2025.04.16 |
[백준] 21736: 헌내기는 친구가 필요해 (0) | 2025.03.27 |