반응형
1446번: 지름길
첫째 줄에 지름길의 개수 N과 고속도로의 길이 D가 주어진다. N은 12 이하인 양의 정수이고, D는 10,000보다 작거나 같은 자연수이다. 다음 N개의 줄에 지름길의 시작 위치, 도착 위치, 지름길의 길이
www.acmicpc.net
◎ 문제풀이
DP 발상이 가능하면 쉽게 풀 수 있는 문제이다.
어느 한 지점에 도착할 수 있는 경우는 2가지이다.
1) 바로 옆에서 1 이동하는 경우
2) 지름길로 이동하는 경우
지름길로 이동하는 경우는 여러가지가 될 수 있다. 그러므로 여러 가지 경우 중에서 가장 최소인 비용을 기억(메모리제이션) 해놓고 다음 지점의 최소비용 구할 때 사용하면 된다.
0부터 목표지점 D까지 Bottom-Up 방식으로 1씩 dp 값을 구하는 방식으로 문제를 풀면 된다.
◎ 코드
import java.io.*;
import java.util.*;
//BOJ1446 지름길
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int d = Integer.parseInt(st.nextToken());
int[] dp = new int[d+1];
HashMap<Integer, List<int[]>> map = new HashMap<>();
for (int i = 0; i < n; i++) {
st = new StringTokenizer(br.readLine());
int start = Integer.parseInt(st.nextToken());
int end = Integer.parseInt(st.nextToken());
int dist = Integer.parseInt(st.nextToken());
List<int[]> shortCut = map.getOrDefault(end, new ArrayList<>());
shortCut.add(new int[]{start, dist});
map.put(end, shortCut);
}
dp[0] = 0;
for (int i = 1; i <= d; i++) {
int minDist = dp[i - 1] + 1;
if (map.containsKey(i)) {
for (int[] shortCut : map.get(i)) {
minDist = Math.min(minDist, dp[shortCut[0]] + shortCut[1]);
}
}
dp[i] = minDist;
}
System.out.println(dp[d]);
}
}
반응형
'문제풀이 > DP' 카테고리의 다른 글
[PS] BOJ12865 평범한 배낭 ( DP ) with JAVA (0) | 2024.02.23 |
---|---|
[PS] BOJ17484 진우의 달 여행 ( DP ) with JAVA (0) | 2024.01.27 |
[PS] BOJ15989 1,2,3 더하기4 ( dp ) with JAVA (0) | 2023.10.18 |
[PS] BOJ11066 파일 합치기 ( dp ) with JAVA (0) | 2023.09.26 |
[PS] BOJ1520 내리막 길 ( DP + DFS ) with JAVA (0) | 2023.09.11 |