728x90
문제
https://www.acmicpc.net/problem/1916
1916번: 최소비용 구하기
첫째 줄에 도시의 개수 N(1 ≤ N ≤ 1,000)이 주어지고 둘째 줄에는 버스의 개수 M(1 ≤ M ≤ 100,000)이 주어진다. 그리고 셋째 줄부터 M+2줄까지 다음과 같은 버스의 정보가 주어진다. 먼저 처음에는 그
www.acmicpc.net
어떻게 풀 것인가?
문제의 제목부터가 "최소비용 구하기" 이다.
그래서 다익스트라 최단경로 구하는 알고리즘을 사용하였다.
사실 그래서 처음 접근 자체는 크게 어렵지 않았다.
내 코드의 핵심은 "우선순위 큐를 활용한 다익스트라 최단 경로 탐색" 이라고 볼 수있다.
우선순위 큐를 사용하는 다익스트라 알고리즘의 시간 복잡도는 O((V + E) log V) 이다. PriorityQueue로 인해 O(log V) 연산을 하므로 효율적이다.
- 그래프 입력 방식: 인접 리스트 ArrayList<Node>[] 사용
- 우선순위 큐 (PriorityQueue) 를 사용하여 최소 비용부터 탐색
- 시간 복잡도 O((V + E) log V) 로 최적화
- 출력 시 최단 거리 dist[end] 출력
풀면서 놓쳤던점
X
이 문제를 통해 얻어갈 것
다익스트라 알고리즘
내 코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
// 백준알고리즘 1916번 최소비용 구하기
public class Main {
static int N, M;
static int start, end;
static ArrayList<Node>[] graph;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine());
M = Integer.parseInt(br.readLine());
graph = new ArrayList[N + 1];
for (int i = 0; i <= N; i++) graph[i] = new ArrayList<>();
for (int i = 0; i < M; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
int v = Integer.parseInt(st.nextToken());
int w = Integer.parseInt(st.nextToken());
int cost = Integer.parseInt(st.nextToken());
graph[v].add(new Node(w, cost));
}
StringTokenizer st = new StringTokenizer(br.readLine());
start = Integer.parseInt(st.nextToken());
end = Integer.parseInt(st.nextToken());
Dijkstra();
}
public static void Dijkstra() {
boolean[] check = new boolean[N + 1];
int[] dist = new int[N + 1];
int INF = Integer.MAX_VALUE;
Arrays.fill(dist, INF);
dist[start] = 0;
PriorityQueue<Node> pq = new PriorityQueue<>();
pq.offer(new Node(start, 0));
while (!pq.isEmpty()) {
int nowVertex = pq.poll().index;
if (check[nowVertex]) continue;
check[nowVertex] = true;
//index의 연결된 정점 비교
for (Node next : graph[nowVertex]) {
if (dist[next.index] > dist[nowVertex] + next.cost) {
dist[next.index] = dist[nowVertex] + next.cost;
pq.offer(new Node(next.index, dist[next.index]));
}
}
}
System.out.print(dist[end]);
}
}
class Node implements Comparable<Node> {
int index;
int cost;
public Node(int index, int cost) {
this.index = index;
this.cost = cost;
}
@Override
public int compareTo(Node o) {
return Integer.compare(this.cost, o.cost);
}
}
참고
[알고리즘/Java]다익스트라(Dijkstra) 알고리즘
✔ 목차 다익스트라 알고리즘이란? 다익스트라 알고리즘 과정 다익스트라 알고리즘 구현 - Java 🔎 다익스트라 알고리즘이란? > 그래프 최단 거리 구하는 알고리즘 1. 다익스트라(Dijkstra) 벨만-포
velog.io
728x90
'BaekJoon' 카테고리의 다른 글
[BaekJoon] 1655번 가운데를 말해요. (Java) 문제 풀이 [Gold 2] (0) | 2025.02.20 |
---|---|
[BaekJoon] 1941번 소문난 칠공주 (Java) 문제 풀이 [Gold 3] (0) | 2025.02.20 |
[BaekJoon] 11729번 하노이 탑 이동 순서 (Java) 문제 풀이 [Gold 5] (2) | 2025.02.13 |
[BaekJoon] 2133번 타일 채우기 (Java) 문제 풀이 [Gold 4] (0) | 2025.02.13 |
[BaekJoon] 11758번 CCW (Java) 문제 풀이 [Gold 5] (0) | 2025.02.13 |