BOJ_1202_보석 도둑_java
2023. 2. 18. 14:41ㆍAlgorithm/BOJ
728x90
https://www.acmicpc.net/problem/1202
1202번: 보석 도둑
첫째 줄에 N과 K가 주어진다. (1 ≤ N, K ≤ 300,000) 다음 N개 줄에는 각 보석의 정보 Mi와 Vi가 주어진다. (0 ≤ Mi, Vi ≤ 1,000,000) 다음 K개 줄에는 가방에 담을 수 있는 최대 무게 Ci가 주어진다. (1 ≤ Ci
www.acmicpc.net
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
/**
백준 1202번 보석도둑
골드 2
*/
public class BOJ_1202_보석도둑 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int N = Integer.parseInt(st.nextToken()); // 보석 수
int K = Integer.parseInt(st.nextToken()); // 가방 수
int[] M = new int[N]; // 보석의 무게
int[] V = new int[N]; // 보석의 가격
Jewel[] jewels = new Jewel[N];
int[] C = new int[K]; // 각 가방의 최대 무게 - 보석 1개만 가능
for (int i = 0; i< N; i++){
st = new StringTokenizer(br.readLine());
M[i] = Integer.parseInt(st.nextToken());
V[i] = Integer.parseInt(st.nextToken());
jewels[i] = new Jewel(M[i], V[i]);
}
for (int i = 0; i< K; i++){
C[i] = Integer.parseInt(br.readLine());
}
long ans = solution(N, K, jewels, C);
System.out.println(ans);
}
public static long solution(int N, int K, Jewel[] jewels, int[] C){
long ans = 0;
// Jewel 배열 무게 순 정렬
Arrays.sort(jewels, (o1, o2) -> o1.weight - o2.weight == 0 ? o1.price - o2.price : o1.weight - o2.weight);
// 가방 수용량 순 정렬
Arrays.sort(C);
// 우선순위 큐
PriorityQueue<Integer> jewelsQueue = new PriorityQueue<>(Comparator.reverseOrder());
int idx = 0;
for (int i = 0; i<K; i++){ // 작은 크기 순 가방
while (idx < N && jewels[idx].weight <= C[i]){ // 해당 가방보다 작은 보석 입력
jewelsQueue.offer(jewels[idx++].price);
}
if(!jewelsQueue.isEmpty()){ // 해당 가방에 넣을수 있는 가장 큰 가치 보석
ans+=jewelsQueue.poll();
}
}
return ans;
}
public static class Jewel{
int weight;
int price;
public Jewel(int weight, int price){
this.weight = weight;
this.price = price;
}
@Override
public String toString() {
return "Jewel{" +
"weight=" + weight +
", price=" + price +
'}';
}
}
}
'Algorithm > BOJ' 카테고리의 다른 글
BOJ_12100_2048(Easy)_java (0) | 2023.02.22 |
---|---|
BOJ_1644_소수의 연속합_java (0) | 2023.02.14 |
BOJ_16724_피리 부는 사나이_java (0) | 2023.02.13 |
BOJ_9466_텀 프로젝트_java (0) | 2023.02.13 |
BOJ_2342_Dance Dance Revolution_java (0) | 2023.02.10 |