설명
“A라는 지원자를 다른 모든 지원자와 일대일 비교해서 키와 몸무게 모두 A지원자 보다 높은 (크고, 무겁다) 지원자가 존재하면 A지원자는 탈락하고, 그렇지 않으면 선발된다.”
씨름 선수로 뽑히는 최대 인원을 출력하세요.
예시
5
172 67
183 65
180 70
170 72
181 60
3
풀이
1. 먼저 키가 큰 순서대로 정렬을 해눚다. implements Comparable하고 @Override로 public int compareTo정의해준다.
2. 그리고 한명씩 돌면서
max보다 몸무게가 큰 사람이 있다면 그 사람들은 cnt에 추가해준다.
나머지는 다 탈락이다.(몸무게랑 키 모두 앞에사람보다 작음으로)
import java.util.*;
class Person implements Comparable<Person>{
int h, w;
public Person(int h, int w) {
this.h=h;
this.w=w;
}
@Override
public int compareTo(Person P) {
return P.h-this.h;
}
}
class Main {
private void solution(ArrayList<Person> list) {
Collections.sort(list);
int max= Integer.MIN_VALUE;
int cnt=0;
for(Person p: list) {
if(p.w>max) {
cnt++;
max=p.w;
}
}
System.out.println(cnt);
}
public static void main(String[] args){
Main T = new Main();
Scanner sc = new Scanner(System.in);
int n= sc.nextInt();
ArrayList<Person> list = new ArrayList<>();
for(int i=0; i<n; i++) {
int a= sc.nextInt();
int b= sc.nextInt();
list.add(new Person(a, b));
}
T.solution(list);
}
}
'알고리즘기초 > Greedy' 카테고리의 다른 글
| 04. 최대 수입 스케쥴 (2) | 2022.10.03 |
|---|---|
| 03. 결혼식 (0) | 2022.10.01 |
| 02. 회의실배정 (0) | 2022.10.01 |