-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathDjikstras.java
More file actions
40 lines (39 loc) · 933 Bytes
/
Djikstras.java
File metadata and controls
40 lines (39 loc) · 933 Bytes
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
class Djikstras {
static int n, s;
static ArrayDeque[] edges;
static long[] d;
public static void main (String[] args){
PriorityQueue<state> pq = new PriorityQueue<>();
d[s] = 0;
pq.add(new state(s, 0));
while(!pq.isEmpty()){
state curr = pq.poll();
if(curr.d > d[curr.i]) continue;
for(edge e : (ArrayDeque<edge>) edges[curr.i]){
long currd = d[curr.i] + e.w;
if(currd < d[e.v]){
d[e.v] = currd;
pq.add(new state(e.v, currd));
}
}
}
}
static class edge{
int v, w;
edge(int vv, int ww){
v = vv;
w = ww;
}
}
static class state implements Comparable<state>{
int i;
long d;
state(int ii, long dd){
i = ii;
d = dd;
}
public int compareTo(state in){
return Long.compare(d, in.d);
}
}
}