다익스트라 문제이다. BFS와 헷갈리지만 다른 점은 있다. BFS는 모든 간선의 가중치가 같지만 다익스트라는 다르다는 점이다.
int[] costs = new int[n + 1];
Arrays.fill(costs, Integer.MAX_VALUE);
배열은 1부터 시작하기 때문에 n+1까지 생성하고 배열 안에 가장 큰 수를 입력한다.
static class City implements Comparable<City> {
int next;
int cost;
City(int next, int cost) {
this.next = next;
this.cost = cost;
}
@Override
public int compareTo(City o) {
return this.cost - o.cost;
}
}
PriorityQueue<City> q = new PriorityQueue<>();
q.add(new City(start, 0));
costs[start] = 0;
while (!q.isEmpty()) {
City city = q.poll();
if (!visit[city.next]) {
visit[city.next] = true;
for (City c : arr[city.next]) {
if (!visit[c.next] && costs[city.next] + c.cost < costs[c.next]) {
costs[c.next] = costs[city.next] + c.cost;
q.add(new City(c.next, costs[c.next]));
}
}
}
}