-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeapMinCostRopeJoin.java
More file actions
98 lines (85 loc) · 2.53 KB
/
HeapMinCostRopeJoin.java
File metadata and controls
98 lines (85 loc) · 2.53 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
import java.util.*;
public class HeapMinCostRopeJoin {
public static int solve(ArrayList<Integer> A) {
int n = A.size();
// create heap out of available lengths
int h[] = new int[n];
createHeap(A, h);
int heapEndPtr = n-1;
int cost = 0;
while(heapEndPtr > 0)
{
int first = h[0];
// System.out.print("first : " + first);
swap(h, 0, n-1);
h[n-1] = Integer.MAX_VALUE;
heapEndPtr--;
heapify(h);
int second = h[0];
// System.out.print("second : " + second);
int newLength = first + second;
cost = cost + newLength;
h[0] = newLength;
heapify(h);
}
return cost;
}
private static void swap(int h[], int p, int q)
{
int tmp = h[p];
h[p] = h[q];
h[q] = tmp;
}
private static void createHeap(ArrayList<Integer> A, int[] h)
{
int n = A.size();
h[0] = A.get(0);
for(int i=1; i<n; i++)
{
h[i] = A.get(i);
int ptr = i;
int parent = (ptr-1)/2;
while(ptr >=0 && h[ptr] < h[parent])
{
swap(h, ptr, parent);
ptr = parent;
parent = (ptr-1)/2;
}
/*System.out.println();
for(int l=0; l<n; l++)
System.out.print(" " + h[l]);*/
}
// System.out.print("original heap --> ");
}
private static void heapify(int h[])
{
int n = h.length;
/*for(int i=0; i<n; i++)
System.out.print(" " + h[i]);*/
// System.out.println();
int curr = 0;
int leftChild = 2*curr+1;
int rightChild = 2*curr+2;
while(curr < n && leftChild<n && rightChild<n && (h[curr]>h[leftChild] || h[curr]>h[rightChild]))
{
int smallestChildPtr = h[leftChild] < h[rightChild] ? (leftChild) : (rightChild);
swap(h, curr, smallestChildPtr);
curr = smallestChildPtr;
leftChild = 2*curr+1;
rightChild = 2*curr+2;
}
/*for(int i=0; i<n; i++)
System.out.print(" " + h[i]);*/
}
public static void main(String args[])
{
//create arrayList
ArrayList<Integer> arr = new ArrayList<>();
arr.add(4);
arr.add(1);
arr.add(2);
arr.add(3);
arr.add(5);
System.out.println("cost = " + solve(arr));
}
}