-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprims.java
More file actions
77 lines (62 loc) · 1.97 KB
/
Copy pathprims.java
File metadata and controls
77 lines (62 loc) · 1.97 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
package templates;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.PriorityQueue;
public class prims {
static long inf = (long) 4e18;
static long[] dists;
static boolean[] visited;
static ArrayList<ArrayList<long[]>> adj;/* adjacency list with weight */
static ArrayList<ArrayList<long[]>> mst;
// initialisation
public static void init(int n) {
dists = new long[n];
visited = new boolean[n];
adj = new ArrayList<>();
mst = new ArrayList<>();
for (int i = 0; i < n; i++) {
adj.add(new ArrayList<>());
mst.add(new ArrayList<>());
}
}
// addedge
public static void addEdge(int a, int b, long wt) {
adj.get(a).add(new long[] { wt, b });
adj.get(b).add(new long[] { wt, a });
}
// prims
public static void run(int src) {
Arrays.fill(dists, inf);
Arrays.fill(visited, false);
PriorityQueue<long[]> pq = new PriorityQueue<>((a, b) -> {
if (a[0] > b[0])
return 1;
else if (a[0] == b[0])
return 0;
else
return -1;
});/* (dist,vertex1,vertex2) */
dists[src] = 0;
for (long[] x : adj.get(src))
pq.add(new long[] { x[0], x[1], src });
long count=0;
while (!pq.isEmpty() && count!=visited.length-1) {
long[] foc = pq.poll();
int v = (int) foc[1];
if (visited[v])
continue;
visited[v] = true;
mst.get((int)foc[2]).add(new long[]{foc[1],foc[0]});
mst.get((int)foc[1]).add(new long[]{foc[2],foc[0]});
count++;
for (long[] x : adj.get(v)) {
long d = x[0];
int u = (int) x[1];
if (d < dists[u]) {
dists[u] = d;
pq.add(new long[] { d, u, v });
}
}
}
}
}