05-16 14:15
Recent Posts
Recent Comments
๊ด€๋ฆฌ ๋ฉ”๋‰ด

miinsun

[Algorithm]์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ž๋ฐ”_71 ์ตœ๋Œ€ ์ˆ˜์ž… ์Šค์ผ€์ฅด :: PriorityQueue ๋ณธ๋ฌธ

Algorithm/Java

[Algorithm]์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ž๋ฐ”_71 ์ตœ๋Œ€ ์ˆ˜์ž… ์Šค์ผ€์ฅด :: PriorityQueue

miinsun 2022. 3. 9. 21:50

 

๐Ÿ’ฌ ๋ฌธ์ œ ์„ค๋ช…

ํ˜„์ˆ˜๋Š” ์œ ๋ช…ํ•œ ๊ฐ•์—ฐ์ž์ด๋‹ค. N๊ฐœ์ด ๊ธฐ์—…์—์„œ ๊ฐ•์—ฐ ์š”์ฒญ์„ ํ•ด์™”๋‹ค.
๊ฐ ๊ธฐ์—…์€ D์ผ ์•ˆ์— ์™€์„œ ๊ฐ•์—ฐ์„ ํ•ด ์ฃผ๋ฉด M๋งŒํผ์˜ ๊ฐ•์—ฐ๋ฃŒ๋ฅผ ์ฃผ๊ธฐ๋กœ ํ–ˆ๋‹ค.

๊ฐ ๊ธฐ์—…์ด ์š”์ฒญํ•œ D์™€ M๋ฅผ ๋ฐ”ํƒ•์œผ๋กœ ๊ฐ€์žฅ ๋งŽ์„ ๋ˆ์„ ๋ฒŒ ์ˆ˜ ์žˆ๋„๋ก ๊ฐ•์—ฐ ์Šค์ผ€์ฅด์„ ์งœ์•ผ ํ•œ๋‹ค.
๋‹จ ๊ฐ•์—ฐ์˜ ํŠน์„ฑ์ƒ ํ˜„์ˆ˜๋Š” ํ•˜๋ฃจ์— ํ•˜๋‚˜์˜ ๊ธฐ์—…์—์„œ๋งŒ ๊ฐ•์—ฐ์„ ํ•  ์ˆ˜ ์žˆ๋‹ค.

 

๐Ÿ”จ ์ž…์ถœ๋ ฅ ์˜ˆ

์ž…๋ ฅ 

  • ์ฒซ ๋ฒˆ์งธ ์ค„์— ์ž์—ฐ์ˆ˜ N(1<=N<=10,000)์ด ์ฃผ์–ด์ง€๊ณ 
  • ๋‹ค์Œ N๊ฐœ์˜ ์ค„์— M(1<=M<=10,000)๊ณผ D(1<=D<=10,000)๊ฐ€ ์ฐจ๋ก€๋กœ ์ฃผ์–ด์ง„๋‹ค.
6
50 2
20 1
40 2
60 3
30 3
30 1

 

์ถœ๋ ฅ - ์ฒซ ๋ฒˆ์งธ ์ค„์— ์ตœ๋Œ€๋กœ ๋ฒŒ ์ˆ˜ ์žˆ๋Š” ์ˆ˜์ž…์„ ์ถœ๋ ฅํ•œ๋‹ค.

150

 

 

โ€‹

๐Ÿ’ป Solution.java

/* ์ตœ๋Œ€ ์ˆ˜์ž… ์Šค์ผ€์ฅด :: Priority Queue */

import java.util.*;

class Lecture implements Comparable<Lecture>{
	public int money;
	public int time;
	
	Lecture(int money, int time){
		this.money = money;
		this.time = time;
	}
	
	@Override
	public int compareTo(Lecture o) { //object๊ฐ€ ๋” ํฌ๋ฉด ์Œ์ˆ˜ ๋ฆฌํ„ด, this๊ฐ€ ๋” ํฌ๋ฉด ์–‘์ˆ˜ ๋ฆฌํ„ด, ๊ฐ™์€ ๊ฐ’์€ 0 ๋ฆฌํ„ด
		return o.time - this.time; // Object์—์„œ ์ง€๊ธˆ ๊ฐ’ ๋นผ๋ฉด ๋‚ด๋ฆผ์ฐจ ์ˆœ 
	} 
}

public class Main {
	static int max = Integer.MIN_VALUE, n;

	public int solution(ArrayList<Lecture> arr, int n) {
		int answer = 0;
		PriorityQueue<Integer> pQ = new PriorityQueue<>(Collections.reverseOrder()); // ์ œ์ผ ํฐ ๊ฐ’์„ ์šฐ์„  ์ˆœ์œ„๋กœ ์ •
		Collections.sort(arr);
		
		int j = 0;
		for(int i = max; i >= 1; i--) {
			for(; j < n; j++) {
				if(arr.get(j).time < i) break;
				pQ.offer(arr.get(j).money);
			}
			
			if(!pQ.isEmpty()) answer += pQ.poll(); // ๊ฐ€์žฅ ํฐ ๊ฐ’์„ poll
		}
		
		return answer;
 	}
	
	public static void main(String[] args){
		Main main = new Main();
		Scanner sc = new Scanner(System.in);
		
		n = sc.nextInt();
		ArrayList<Lecture> arr = new ArrayList<>();
		
		for(int i = 0; i < n; i++) {
			int m = sc.nextInt();
			int d = sc.nextInt();
			arr.add(new Lecture(m, d));
			if(d > max) max = d;
		}
		
		System.out.println(main.solution(arr, n));
		
		sc.close();
		return ;
	}
}

 

 

 

Comments