-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJ1753_2.java
More file actions
73 lines (55 loc) · 1.86 KB
/
J1753_2.java
File metadata and controls
73 lines (55 loc) · 1.86 KB
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
package TIL;
import java.io.*;
import java.util.*;
public class J1753_2 {
static ArrayList<int[]>[] list;
static int[] arr;
static boolean[] visited;
public static void main(String[] args) throws IOException {
BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));
String[] input = buffer.readLine().split(" ");
int V = Integer.parseInt(input[0]);
int E = Integer.parseInt(input[1]);
list = new ArrayList[V+1];
for(int i = 0 ; i <= V; i++) {
list[i] = new ArrayList<>();
}
int start = Integer.parseInt(buffer.readLine());
for(int i = 0; i < E; i++) {
input = buffer.readLine().split(" ");
int node = Integer.parseInt(input[0]);
int edge = Integer.parseInt(input[1]);
int weight = Integer.parseInt(input[2]);
list[node].add(new int[] {edge, weight});
}
arr = new int[V+1];
visited = new boolean[V+1];
for(int i = 0 ; i <= V ; i++) {
if(i == start) continue;
arr[i] = Integer.MAX_VALUE;
}
dikstra(start);
for(int i = 1; i <= V; i++) {
if(arr[i] == Integer.MAX_VALUE) System.out.println("INF");
else System.out.println(arr[i]);
}
}
public static void dikstra(int n) {
visited[n] = true;
for(int[] node : list[n]) {
if(!visited[node[0]]) {
arr[node[0]]= Math.min(arr[n]+node[1], arr[node[0]]);
// dikstra(node[0]);
}
}
int min = Integer.MAX_VALUE;
int index = 0;
for(int i = 1; i < arr.length; i++) {
if(!visited[i]) {
if(arr[i] < min) index = i;
min = Math.min(min, arr[i]);
}
}
if(!visited[index]) dikstra(index);
}
}