📌 문제
📌 내가 풀이한 방법
⬇️ 첫 번째 값 풀이 ( ⛔ 오답 )
static public int solution(Speech[] arr,int n) {
PriorityQueue<Integer> pQ = new PriorityQueue<>(Collections.reverseOrder());
Arrays.sort(arr);
int max = arr[0].d;
int sum=0;
for(int i=0;i<n;i++) {
if(max==arr[i].d) {
pQ.offer(arr[i].p);
}else {
sum+=pQ.poll();
pQ.offer(arr[i].p);
max-=1;
}
}
sum+=pQ.poll();
return sum;
}
오답 이유
따라서 정답인 풀이는 다음과 같다
⬇️ 정답 풀이
static public int solution(Speech[] arr,int n) {
PriorityQueue<Integer> pQ = new PriorityQueue<>(Collections.reverseOrder());
Arrays.sort(arr);
int max = arr[0].d;
int sum=0;
int j=0;
for(int i=max;i>=1;i--) {
for(;j<n;j++){
if(arr[j].d<i) break;
else pQ.offer(arr[j].p);
}
if(!pQ.isEmpty()) sum+= pQ.poll();
}
return sum;
}
▪️ j를 밖에 둔 이유 : j값을 저장해서 그 순서부터 순환해야함
만약, for(int j=0;j<n;j++)과 같이 지정한다면 계속 큰 값이 들어감
📌 전체 정답 코드
import java.util.*;
public class Main {
static public int solution(Speech[] arr,int n) {
PriorityQueue<Integer> pQ = new PriorityQueue<>(Collections.reverseOrder());
Arrays.sort(arr);
int max = arr[0].d;
int sum=0;
int j=0;
for(int i=max;i>=1;i--) {
for(;j<n;j++){
System.out.println(arr[j].p+": "+arr[j].d);
if(arr[j].d<i) break;
else pQ.offer(arr[j].p);
}
if(!pQ.isEmpty()) sum+= pQ.poll();
}
return sum;
}
static public void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
Speech[] arr = new Speech[n];
for(int i=0;i<n;i++) {
arr[i] = new Speech(sc.nextInt(),sc.nextInt());
}
System.out.println(solution(arr,n));
}
static class Speech implements Comparable<Speech>{
public int p,d;//pay,day
Speech(int p,int d){
this.p=p;
this.d=d;
}
@Override
public int compareTo(Speech s) {
return s.d-this.d;
}
}
}