๋ฌธ์ (์ถ์ฒ: 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๋ฅผ ์ดํด๋ณด๋ฉฐ ์ต๋ ์ธ์์ ๊ตฌํด ์ถ๋ ฅํ๋ค.

'๐Algorithm > ๐ฅBaekjoon' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| [Baekjoon] 19622_ํ์์ค ๋ฐฐ์ 3 (0) | 2026.02.12 |
|---|---|
| [Baekjoon] 5953_Profits (0) | 2026.02.10 |
| [Baekjoon] 1699_์ ๊ณฑ์์ ํฉ (0) | 2026.02.09 |
| [Baekjoon] 4097_์์ต (0) | 2026.01.30 |
| [Baekjoon] 18353_๋ณ์ฌ ๋ฐฐ์นํ๊ธฐ (0) | 2026.01.29 |