문제
도서관 문제 바로가기
제출 코드(JAVA)
코드 제출
import java.util.*;
public class 도서관_1461 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int size = scan.nextInt();
int box = scan.nextInt();
ArrayList<Integer> books = new ArrayList<>();
for(int i = 0; i < size; i++) {
books.add(scan.nextInt());
}
int result = solution(books, box);
System.out.println(result);
}
private static int solution(ArrayList<Integer> books, int boxSize) {
Queue<Integer> positive = new PriorityQueue<>(Collections.reverseOrder());
Queue<Integer> negative = new PriorityQueue<>(Collections.reverseOrder());
books.forEach(i -> {
if (i >= 0) {
positive.add(i);
} else {
negative.add(i*-1);
}
});
int element;
int max = 0;
int sum = 0;
while (!positive.isEmpty()) {
for (int i = 0; i < boxSize; i++) {
if (positive.isEmpty())
continue;
element = positive.poll();
if (i == 0) {
sum += Math.abs(element);
if (Math.abs(element) > max) {
max = Math.abs(element);
}
}
}
}
while (!negative.isEmpty()) {
for (int i = 0; i < boxSize; i++) {
if (negative.isEmpty())
continue;
element = negative.poll();
if (i == 0) {
sum += element;
if (element > max) {
max = element;
}
}
}
}
return sum * 2 - max;
}
}
- 먼 곳부터 가까운 곳으로 순회
- 결국 왕복이기에 가장 먼 곳만 결과에 합산
- 마지막으로 간 지점은 돌아올 필요가 없기에 한번의 거리만 측정
- 즉, 한번에 담을 수 있는 수량만큼 그룹화하여 전체 합산 후, 가장 먼 곳만 빼주면 끝