๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
2๏ธโƒฃ Java/Problem Solving

[Java Algorithm] ์ตœ์†Œ ํšŒ์˜์‹ค ๊ฐœ์ˆ˜ BOJ #19598

by seolhee2750 2022. 8. 31.
๋ฌธ์ œ

https://www.acmicpc.net/problem/2294

 

2294๋ฒˆ: ๋™์ „ 2

์ฒซ์งธ ์ค„์— n, k๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. (1 ≤ n ≤ 100, 1 ≤ k ≤ 10,000) ๋‹ค์Œ n๊ฐœ์˜ ์ค„์—๋Š” ๊ฐ๊ฐ์˜ ๋™์ „์˜ ๊ฐ€์น˜๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๋™์ „์˜ ๊ฐ€์น˜๋Š” 100,000๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์€ ์ž์—ฐ์ˆ˜์ด๋‹ค. ๊ฐ€์น˜๊ฐ€ ๊ฐ™์€ ๋™์ „์ด ์—ฌ๋Ÿฌ ๋ฒˆ ์ฃผ

www.acmicpc.net

 

๋‚ด ๋ฌธ์ œ ํ’€์ด
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.StringTokenizer;

public class BOJ_19598 {

	static class Meetings implements Comparable<Meetings> {
		int s, e;

		public Meetings(int s, int e) {
			super();
			this.s = s;
			this.e = e;
		}

		@Override
		public int compareTo(Meetings o) {
			return this.s - o.s; // ์‹œ์ž‘ ์‹œ๊ฐ„ ๊ธฐ์ค€ ์ •๋ ฌ
		}	
	}

	public static void main(String[] args) throws Exception {
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st;

		int n = Integer.parseInt(in.readLine());
		Meetings[] meetings = new Meetings[n];
		for(int i = 0; i < n; i++) {
			st = new StringTokenizer(in.readLine());
			meetings[i] = new Meetings(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()));
		}
		Arrays.sort(meetings);

		PriorityQueue<Integer> endTimes = new PriorityQueue<>();
		endTimes.add(meetings[0].e);
		for(int i = 1; i < meetings.length; i++) {
			if(endTimes.peek() <= meetings[i].s) {
				endTimes.poll();
			}
			endTimes.add(meetings[i].e);
		}

		System.out.println(endTimes.size());
	}
}

๐Ÿ‘‰ Greedy ๋ฌธ์ œ

  • ์‹œ์ž‘ ์‹œ๊ฐ„ ๊ธฐ์ค€์œผ๋กœ ์ •๋ ฌํ•˜๊ณ , ์ฒซ ๋ฒˆ์งธ ํšŒ์˜๋ถ€ํ„ฐ ๋๋‚˜๋Š” ์‹œ๊ฐ„์„ PriorityQueue์ธ endTimes์— ๋„ฃ์—ˆ๋‹ค.
  • ์ฒซ ๋ฒˆ์งธ ํšŒ์˜๋Š” ๋น„๊ต ๋Œ€์ƒ์ด ์—†์œผ๋ฏ€๋กœ ๊ทธ๋ƒฅ ๋„ฃ์–ด์ฃผ์—ˆ๊ณ ,
    ๋‘ ๋ฒˆ์งธ ํšŒ์˜๋ถ€ํ„ฐ๋Š” endTimes์˜ ์ฒซ ๋ฒˆ์งธ ๋๋‚˜๋Š” ์‹œ๊ฐ„๊ณผ ๋น„๊ตํ•˜์—ฌ ๋„ฃ๋Š” ๊ฒƒ์„ ๋ฐ˜๋ณตํ–ˆ๋‹ค.
  • ํ˜„์žฌ ํšŒ์˜์˜ ์‹œ์ž‘ ์‹œ๊ฐ„์ด endTimes ์ฒซ ๋ฒˆ์งธ ๋๋‚˜๋Š” ์‹œ๊ฐ„๊ณผ ๊ฐ™๊ฑฐ๋‚˜ ๋Š๋ฆฌ๋‹ค๋ฉด,
    ํ•˜๋‚˜์˜ ํšŒ์˜์‹ค์„ ๊ณต์œ ํ•  ์ˆ˜ ์žˆ๋Š” ๊ฒƒ์ด๋ฏ€๋กœ endTimes์˜ ์ฒซ ๋ฒˆ์งธ ํšŒ์˜๋ฅผ ๊บผ๋‚ด์ฃผ๊ณ ,
    ํ˜„์žฌ ํšŒ์˜์˜ ๋๋‚˜๋Š” ์‹œ๊ฐ„์„ ๋Œ€์‹ ํ•ด์„œ ๋„ฃ์–ด์ฃผ์—ˆ๋‹ค. (== ํ•ด๋‹น ํšŒ์˜์‹ค์˜ ๋๋‚˜๋Š” ์‹œ๊ฐ„ ์—…๋ฐ์ดํŠธ)
  • ๋ชจ๋“  ํšŒ์˜์‹ค ํƒ์ƒ‰์„ ๋๋‚œ ํ›„ ์™„์„ฑ๋œ endTimes์˜ size๊ฐ€ ์ด ํšŒ์˜์‹ค์˜ ๊ฐœ์ˆ˜๊ฐ€ ๋œ๋‹ค.

 

๐Ÿ’ก ํ”ผ๋“œ๋ฐฑ
  • ๊ทธ๋ฆฌ๋””๋Š” ํ•ญ์ƒ ์ข€ ํ—ท๊ฐˆ๋ฆฌ๋Š” ๋Š๋‚Œ์ด ์žˆ๋”๋ผ..!! ์ด ๋ฌธ์ œ๋„ ๋งˆ์ฐฌ๊ฐ€์ง€,,
    ๋งŽ์ด ํ’€์–ด๋ด์•ผ ํ•  ๊ฒƒ ๊ฐ™๋‹ค.

๋Œ“๊ธ€