-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCHICAGO.java
More file actions
105 lines (80 loc) · 2.15 KB
/
Copy pathCHICAGO.java
File metadata and controls
105 lines (80 loc) · 2.15 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
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
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.PriorityQueue;
import java.util.ArrayList;
import java.util.LinkedList;
class CHICAGO {
public static void main(String[]args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String [] in_arr;
int n, m; //n: number of nodes m: numbber of edges.
boolean [] v;
ArrayList <LinkedList <Node>> adj;
while(true) {
adj = new ArrayList <LinkedList <Node> > ();
String in = br.readLine();
if(in.equals("0"))
break;
in_arr = in.split(" ");
n = Integer.parseInt(in_arr[0]);
m = Integer.parseInt(in_arr[1]);
/* Initialize the ArrayList */
for(int i = 0; i < n; i++) {
adj.add(new LinkedList <Node>());
}
/* Create the adjacency list */
for(int i = 0; i < m; i++) {
in_arr = br.readLine().split(" ");
/* Nodes and edge value read in from stdin */
int n1 = Integer.parseInt(in_arr[0]) - 1;
int n2 = Integer.parseInt(in_arr[1]) - 1;
double e = Double.parseDouble(in_arr[2]) / 100;
/* Insert the nodes in the corresponding adjacency lists */
adj.get(n1).add(new Node(n2, e));
adj.get(n2).add(new Node(n1, e));
}
/* Dijikstra */
PriorityQueue <Node> pq = new PriorityQueue <Node> ();
LinkedList <Node> tmp;
v = new boolean [n];
/* Add the start node to the PriorityQueue */
pq.add(new Node(0,1));
while(!pq.isEmpty()) {
Node curr = pq.remove();
int i = curr.index;
double p = curr.prob;
if(v[i])
continue;
v[i] = true;
if(i == n - 1)
{
System.out.println(String.format("%.6f percent", p * 100));
break;
}
tmp = adj.get(i);
while(!tmp.isEmpty()) {
curr = tmp.remove();
pq.add(new Node(curr.index, curr.prob * p));
}
}
}
}
}
class Node implements Comparable <Node> {
int index;
double prob;
public Node(int i, double p) {
this.index = i;
this.prob = p;
}
public int compareTo(Node n) {
/* Higher probability has higher priority */
if(this.prob == n.prob)
return 0;
else if(this.prob > n.prob)
return -1;
else
return 1;
}
}