ALGORITHM/BOJ
[백준] 1854 K번째 최단경로 찾기
0298
2021. 1. 31. 19:58
1854번: K번째 최단경로 찾기
첫째 줄에 n, m, k가 주어진다. (1 ≤ n ≤ 1000, 0 ≤ m ≤ 2000000, 1 ≤ k ≤ 100) n과 m은 각각 김 조교가 여행을 고려하고 있는 도시들의 개수와, 도시 간에 존재하는 도로의 수이다. 이어지는 m개의 줄에
www.acmicpc.net
2021-01-30
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
public class Main1854 {
public static int N, M, K;
public static List<List<Doro>> list;
public static PriorityQueue<Doro> pq;
public static PriorityQueue<Integer> dist[];
static Comparator<Integer> com = new Comparator<Integer>() { // 정렬
@Override
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
};
public static class Doro implements Comparable<Doro>{
int node;
int time;
public Doro(int node, int time) {
this.node = node;
this.time = time;
}
@Override
public int compareTo(Doro doro) {
return this.time - doro.time;
}
}
public static void solve() {
PriorityQueue<Doro> pq = new PriorityQueue<>();
dist[1].add(0);
pq.add(new Doro(1, 0));
while(!pq.isEmpty()) {
Doro tmp = pq.poll();
int cur = tmp.node;
int time = tmp.time;
for(Doro d: list.get(cur)) {
if(dist[d.node].size() < K) {
dist[d.node].add((time + d.time));
pq.add(new Doro(d.node, (time + d.time)));
} else if(dist[d.node].peek() > time + d.time){ // K만큼만 체크하게 되면 가장 큰 값이 K번쨰 최단경로가 된다.
dist[d.node].poll();
dist[d.node].add(time + d.time);
pq.add(new Doro(d.node, (time + d.time)));
}
}
}
}
public static void main(String[] args) throws Exception {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(bf.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
K = Integer.parseInt(st.nextToken());
list = new ArrayList<>();
dist= new PriorityQueue[N+1];
for(int i = 0; i <= N; i++) {
list.add(new ArrayList<>());
dist[i] = new PriorityQueue<>(com);
}
for(int i = 0; i < M; i++) {
st = new StringTokenizer(bf.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
int c = Integer.parseInt(st.nextToken());
list.get(a).add(new Doro(b, c));
}
solve();
for(int i = 1; i <= N; i++) {
if(dist[i].size() == K) System.out.println(dist[i].peek());
else System.out.println("-1");
}
}
}
|
cs |
#문제풀이
다익스트라 알고리즘으로 푸는 문제이다.
PriorityQueue 타입의 1차원 배열이라는 힌트를 얻고 풀었다. 포인트는 이 배열에 각각 K만큼만 경로의 비용을 저장하는 것이다.