문제
방향그래프가 주어지면 주어진 시작점에서 다른 모든 정점으로의 최단 경로를 구하는 프로그램을 작성하시오. 단, 모든 간선의 가중치는 10 이하의 자연수이다.
입력
첫째 줄에 정점의 개수 V와 간선의 개수 E가 주어진다. (1 ≤ V ≤ 20,000, 1 ≤ E ≤ 300,000) 모든 정점에는 1부터 V까지 번호가 매겨져 있다고 가정한다. 둘째 줄에는 시작 정점의 번호 K(1 ≤ K ≤ V)가 주어진다. 셋째 줄부터 E개의 줄에 걸쳐 각 간선을 나타내는 세 개의 정수 (u, v, w)가 순서대로 주어진다. 이는 u에서 v로 가는 가중치 w인 간선이 존재한다는 뜻이다. u와 v는 서로 다르며 w는 10 이하의 자연수이다. 서로 다른 두 정점 사이에 여러 개의 간선이 존재할 수도 있음에 유의한다.
출력
첫째 줄부터 V개의 줄에 걸쳐, i번째 줄에 i번 정점으로의 최단 경로의 경로값을 출력한다. 시작점 자신은 0으로 출력하고, 경로가 존재하지 않는 경우에는 INF를 출력하면 된다.
import java.util.*;
public class Main {
private static int V; // 노드 개수
private static int E; // 에지 개수
private static int s; // 시작 노드
private static int distance[]; // 최단 거리 배열
private static int INF = Integer.MAX_VALUE;
static ArrayList<Node> arr[]; // Node 타입 정점 인접리스트
public static void dijkstra() {
PriorityQueue<Node> queue = new PriorityQueue<>();
queue.add(new Node(s, 0));
while (!queue.isEmpty()) {
Node node = queue.poll(); // poll : 큐 맨 앞에 있는 값 반환 후 삭제
int vertex = node.vertex; // 노드
int weight = node.weight; // 가중치
if (distance[vertex] < weight) { // 현재 가중치가 더 크면 갱신할 필요 없음(최단 거리 구하는거라)
continue;
}
for (int i = 0; i < arr[vertex].size(); i++) { // 해당 정점과 연결된 것들 탐색
int vertex2 = arr[vertex].get(i).vertex; // arr 배열의 vertex 번째 인덱스 중 i 번째 노드의 vertex 값을 전달
int weight2 = arr[vertex].get(i).weight + weight;
if (distance[vertex2] > weight2) { // 새로운 가중치가 더 최단 경로라면 갱신
distance[vertex2] = weight2;
queue.add(new Node(vertex2, weight2)); // 노드 추가
}
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
V = sc.nextInt();
E = sc.nextInt();
s = sc.nextInt();
arr = new ArrayList[V + 1];
distance = new int[V + 1];
for (int i = 1; i <= V; i++) { // 인접 리스트 초기화
arr[i] = new ArrayList<>();
}
Arrays.fill(distance, INF); // 최대값으로 초기화
distance[s] = 0; // 시작 노드의 가중치는 0
for (int i = 0; i < E; i++) {
int u = sc.nextInt();
int v = sc.nextInt();
int w = sc.nextInt();
arr[u].add(new Node(v ,w)); // 노드 추가
}
dijkstra();
for (int i = 1; i <= V; i++) {
if (distance[i] == INF) {
System.out.println("INF"); // 최대값이라고 표현
} else {
System.out.println(distance[i]); // 시작 노드부터 각 노드까지의 최단 거리 표현
}
}
sc.close();
}
private static class Node implements Comparable<Node> { // 우선 순위 큐로 성능 개선(안하면 시간초과)
int vertex;
int weight;
public Node(int vertex, int weight) {
this.vertex = vertex;
this.weight = weight;
}
@Override // 오버라이드: 재정의
public int compareTo(Node o) {
return weight - o.weight;
}
}
}
반응형
'코딩 테스트 > Java' 카테고리의 다른 글
[백준/Java] 2042 구간 합 구하기 : 세그먼트 트리 (0) | 2023.04.13 |
---|---|
[백준/Java] 1197 최소 스패닝 트리 : 최소 신장 트리 (0) | 2023.04.13 |
[백준/Java] 1516 게임 개발 : 위상 정렬 (0) | 2023.04.13 |
[백준/Java] 1717 집합의 표현 : 유니온 파인드 (0) | 2023.04.12 |
[백준/Java] 1929 소수 구하기 : 에라토스테네스의 체 (0) | 2023.04.12 |