-
Notifications
You must be signed in to change notification settings - Fork 0
/
CountryRoads.java
124 lines (108 loc) · 2.86 KB
/
CountryRoads.java
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
/** http://www.lightoj.com/volume_showproblem.php?problem=1002 #dijkstra #shortest-path */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
class CountryRoads {
private static ArrayList<Node>[] graph = new ArrayList[501];
private static int[] distArr = new int[501];
public static void Dijkstra(int startVertex) {
distArr[startVertex] = 0;
PriorityQueue<Node> pq = new PriorityQueue<>();
pq.add(new Node(startVertex, 0));
while (!pq.isEmpty()) {
Node node = pq.poll();
int id = node.id;
int dist = node.dist;
if (dist > distArr[id]) {
continue;
}
for (Node neighbour : graph[id]) {
int newDist = Math.max(dist, neighbour.dist);
if (newDist < distArr[neighbour.id]) {
distArr[neighbour.id] = newDist;
pq.add(new Node(neighbour.id, newDist));
}
}
}
}
public static void main(String[] args) {
MyScanner sc = new MyScanner(System.in);
int n, m, u, v, w;
int testCases = sc.nextInt();
for (int testcase = 1; testcase < testCases + 1; testcase++) {
n = sc.nextInt();
m = sc.nextInt();
for (int i = 0; i < n; i++) {
graph[i] = new ArrayList<Node>();
distArr[i] = Integer.MAX_VALUE;
}
for (int i = 0; i < m; i++) {
u = sc.nextInt();
v = sc.nextInt();
w = sc.nextInt();
graph[u].add(new Node(v, w));
graph[v].add(new Node(u, w));
}
int startVertex = sc.nextInt();
Dijkstra(startVertex);
System.out.println("Case " + testcase + ":");
for (int i = 0; i < n; i++) {
if (distArr[i] == Integer.MAX_VALUE) {
System.out.println("Impossible");
} else {
System.out.println(distArr[i]);
}
}
}
}
}
class Node implements Comparable<Node> {
int id;
int dist;
Node(int id, int dist) {
this.id = id;
this.dist = dist;
}
public int compareTo(Node other) {
return this.dist - other.dist;
}
}
class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}