Problem Solving/Baekjoon
[백준] 1446 지름길 - Graph Theory / Java
graycode
2023. 1. 24. 15:04
• 문제 링크
1446번: 지름길
첫째 줄에 지름길의 개수 N과 고속도로의 길이 D가 주어진다. N은 12 이하인 양의 정수이고, D는 10,000보다 작거나 같은 자연수이다. 다음 N개의 줄에 지름길의 시작 위치, 도착 위치, 지름길의 길이
www.acmicpc.net
• 풀이 과정
• 풀이 코드
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int d = Integer.parseInt(st.nextToken());
int[] dist = new int[d + 1];
List<Pair>[] graph = new ArrayList[10001];
Arrays.fill(dist, Integer.MAX_VALUE);
for (int i = 0; i < graph.length; i++)
graph[i] = new ArrayList<>();
while (n-- > 0) {
st = new StringTokenizer(br.readLine());
int src = Integer.parseInt(st.nextToken());
int dest = Integer.parseInt(st.nextToken());
int weight = Integer.parseInt(st.nextToken());
if (dest - src > weight)
graph[dest].add(new Pair(src, weight));
}
dist[0] = 0;
for (int i = 1; i <= d; i++) {
if (graph[i].size() > 0) {
for (Pair src : graph[i]) {
if (dist[src.node] + src.weight > dist[i])
continue;
dist[i] = Math.min(dist[i - 1] + 1, dist[src.node] + src.weight);
}
} else
dist[i] = dist[i - 1] + 1;
}
bw.write(String.valueOf(dist[d]));
bw.flush();
}
private static class Pair {
int node, weight;
public Pair(int node, int weight) {
this.node = node;
this.weight = weight;
}
}
}