https://www.acmicpc.net/problem/1916
정답률 32.431%
N개의 도시가 있다. 그리고 한 도시에서 출발하여 다른 도시에 도착하는 M개의 버스가 있다. 우리는 A번째 도시에서 B번째 도시까지 가는데 드는 버스 비용을 최소화 시키려고 한다. A번째 도시에서 B번째 도시까지 가는데 드는 최소비용을 출력하여라. 도시의 번호는 1부터 N까지이다.
5
8
1 2 2
1 3 3
1 4 1
1 5 10
2 4 2
3 4 1
3 5 1
4 5 3
1 5
4
최단경로 문제랑 완전 동일하다. 시작점과 도착점이 주어지고, 최단 거리를 구하는 문제이므로 다익스트라 알고리즘을 사용한다.
import static java.util.Comparator.comparingInt;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
//백준
public class Main {
static List<List<Edge>> adjList = new ArrayList<>();
static int[] dist;
static boolean[] visited;
public static void main(String[] args) throws IOException {
System.setIn(new FileInputStream("src/input.txt"));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
int N = Integer.parseInt(br.readLine()); //도시의 개수
int M = Integer.parseInt(br.readLine()); //버스의 개수
dist = new int[N + 1];
visited = new boolean[N + 1];
for (int i = 0; i <= N; i++) {
adjList.add(new ArrayList<>());
}
for (int i = 0; i < M; i++) {
st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken()); //출발 도시
int b = Integer.parseInt(st.nextToken()); //도착 도시
int c = Integer.parseInt(st.nextToken()); //비용
adjList.get(a).add(new Edge(b, c));
}
st = new StringTokenizer(br.readLine());
int start = Integer.parseInt(st.nextToken());
int destination = Integer.parseInt(st.nextToken());
dijkstra(start);
System.out.println(dist[destination]);
}
static void dijkstra(int node) {
Arrays.fill(dist, Integer.MAX_VALUE);
PriorityQueue<Edge> pq = new PriorityQueue<>(comparingInt(Edge::getWeight));
pq.add(new Edge(node, 0));
dist[node] = 0;
while (!pq.isEmpty()) {
Edge cur = pq.poll();
int curNode = cur.to;
//방문하지 않은 노드일 경우
if (!visited[curNode]) {
visited[curNode] = true;
for (Edge next : adjList.get(curNode)) {
int nextNode = next.to;
int nextWeight = next.weight;
int newDist = dist[curNode] + nextWeight;
if (dist[nextNode] > newDist) {
dist[nextNode] = newDist;
pq.add(new Edge(nextNode, dist[nextNode]));
}
}
}
}
}
static class Edge {
int to;
int weight;
public Edge(int to, int weight) {
this.to = to;
this.weight = weight;
}
public int getWeight() {
return weight;
}
}
}