๐ŸŒžAlgorithm/๐Ÿ”ฅBaekjoon

[Baekjoon] 19621_ํšŒ์˜์‹ค ๋ฐฐ์ • 2

๋ฟŒ์•ผ._. 2026. 2. 11. 15:44
๋ฌธ์ œ(์ถœ์ฒ˜: https://www.acmicpc.net/problem/19621)

< ํšŒ์˜์‹ค ๋ฐฐ์ • 2 >

 

๋ฌธ์ œ ํ’€์ด 

 

ํšŒ์˜๊ฐ€ ๋๋‚˜๋Š” ์‹œ๊ฐ„์„ ๊ธฐ์ค€์œผ๋กœ ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌ ํ›„ dp๋ฅผ ํ™œ์šฉํ•ด ํšŒ์˜๋ฅผ ์ง„ํ–‰ํ•  ์ˆ˜ ์žˆ๋Š” ์ตœ๋Œ€ ์ธ์›์„ ๊ตฌํ•œ๋‹ค. 

 

my solution (Java)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.StringTokenizer;

public class _19621_ { // ํšŒ์˜์‹ค ๋ฐฐ์ • 2
	static class Info {
		private int start;
		private int end;
		private int num;

		public Info(int start, int end, int num) {
			this.start = start;
			this.end = end;
			this.num = num;
		}
	}

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

		int n = Integer.parseInt(bf.readLine());

		ArrayList<Info> list = new ArrayList<>();
		int dp[] = new int[n];

		for (int i = 0; i < n; i++) {
			st = new StringTokenizer(bf.readLine());

			list.add(new Info(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()),
					Integer.parseInt(st.nextToken())));
		}

		Collections.sort(list, new Comparator<Info>() {

			@Override
			public int compare(Info o1, Info o2) {
				return o1.end - o2.end;
			}
		});

		for (int i = 0; i < n; i++) {
			dp[i] = list.get(i).num;
		}

		for (int i = 1; i < n; i++) {
			for (int j = 0; j < i; j++) {
				if (list.get(i).start >= list.get(j).end) {
					dp[i] = Math.max(dp[i], dp[j] + list.get(i).num);
				}
			}
		}

		int result = 0;
		for (int i = 0; i < n; i++) {
			result = Math.max(result, dp[i]);
		}

		System.out.println(result);
	}
}
๋ณ€์ˆ˜)
n : ํšŒ์˜์˜ ์ˆ˜
list : ํšŒ์˜ ์ •๋ณด๋ฅผ ์ €์žฅํ•˜๋Š” ArrayList
dp : ํšŒ์˜๋ฅผ ์ง„ํ–‰ํ•  ์ˆ˜ ์žˆ๋Š” ์ตœ๋Œ€ ์ธ์›์„ ๊ตฌํ•˜๋Š” ๋ฐฐ์—ด
result : ํšŒ์˜๋ฅผ ์ง„ํ–‰ํ•  ์ˆ˜ ์žˆ๋Š” ์ตœ๋Œ€ ์ธ์›

 

ํšŒ์˜์˜ ์ˆ˜๋ฅผ ์ž…๋ ฅ๋ฐ›๋Š”๋‹ค. ํšŒ์˜์˜ ์ˆ˜๋งŒํผ ํšŒ์˜ ์ •๋ณด๋ฅผ ์ž…๋ ฅ๋ฐ›์•„ ArrayList์— ์ €์žฅํ•œ๋‹ค. ArrayList๋ฅผ ํšŒ์˜๊ฐ€ ๋๋‚˜๋Š” ์‹œ๊ฐ„์„ ๊ธฐ์ค€์œผ๋กœ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌํ•œ๋‹ค. dp๋ฅผ ๊ฐ ํšŒ์˜์— ์ฐธ์—ฌํ•˜๋Š” ์ธ์›์œผ๋กœ ์ดˆ๊ธฐํ™”ํ•œ ํ›„ ArrayList๋ฅผ ์‚ดํŽด๋ณด๋ฉฐ ํ˜„์žฌ๊ฐ’๊ณผ ํ˜„์žฌ ํšŒ์˜์™€ ๊ฒน์น˜์ง€ ์•Š๋Š” ์ด์ „ ํšŒ์˜ ์ธ์› + ํ˜„์žฌ ์ฐธ์—ฌ ์ธ์› ์ค‘ ์ตœ๋Œ“๊ฐ’์œผ๋กœ ์—…๋ฐ์ดํŠธํ•œ๋‹ค. ์ตœ์ข… dp๋ฅผ ์‚ดํŽด๋ณด๋ฉฐ ์ตœ๋Œ€ ์ธ์›์„ ๊ตฌํ•ด ์ถœ๋ ฅํ•œ๋‹ค.