본문 바로가기

Language/JAVA

[JAVA][백준 1092][Greedy, Sort] 배 - 컴도리돌이

728x90
728x90
반응형
 

1092번: 배

첫째 줄에 N이 주어진다. N은 50보다 작거나 같은 자연수이다. 둘째 줄에는 각 크레인의 무게 제한이 주어진다. 이 값은 1,000,000보다 작거나 같다. 셋째 줄에는 박스의 수 M이 주어진다. M은 10,000보

www.acmicpc.net


크레인의 무게 제한과 박스의 무게를 "crain", "box" 이름으로 ArrayList로 담았다.

그리고 해당 ArrayList들을 모두 내림차순 정렬을 시켰다.

ArrayList를 내림차순 정렬을 할 때는 Collection.reverseOrder() 함수를 sort안에 명시해주어야 한다.

정렬된 두 ArrayList의 첫 번째 인덱스 값을 비교한다.

만약 크레인의 첫 번째 값이 박스의 첫 번째 값보다 작을 경우  모든 박스를 담을 수 없기 때문에 

-1을 반환해준다.

 

해당 조건을 만족하면 모든 박스를 크레인에 담을 수 있기 때문에

크레인에 i번째에 idx번째 박스를 담는다.

만약 i번째에 idx번째를 담을 수 있다면 

idx번째 박스의 값을 remove 시켜주고, i를 증가시킨다.

담을 수 없을 경우 idx를 증가시킨다.


import java.util.*;
public class Main {
static Scanner sc = new Scanner(System.in);
static int n,m,answer= 0;
static ArrayList<Integer> crain = new ArrayList<>();
static ArrayList<Integer> box = new ArrayList<>();
public static void main(String[] args) throws Exception {
input();
solution();
}
static public void input() throws Exception{
n = sc.nextInt();
for(int i =0; i <n ; i++){
crain.add(sc.nextInt());
}
m = sc.nextInt();
for(int i=0; i<m ; i++){
box.add(sc.nextInt());
}
}
static public void solution(){
Collections.sort(crain,Collections.reverseOrder());
Collections.sort(box,Collections.reverseOrder());
if(crain.get(0) < box.get(0)){
System.out.print(-1);
return;
}
while(!box.isEmpty()){
answer += 1;
int idx = 0;
for(int i=0; i< n ;){
if(crain.get(i) >= box.get(idx)){
box.remove(idx);
i++;
}else {
idx ++;
}
if(idx == box.size()) break;
}
}
System.out.print(answer);
}
}
view raw boj1092.java hosted with ❤ by GitHub

728x90
728x90