5 public class Heap<V, K> {
6 private static final Object[] empty = {};
7 private final Comparator<? super K> cmp;
8 private final Map<V, Integer> index = new IdentityHashMap<>();
9 private Object[] vbuf = empty, kbuf = empty;
12 public Heap(Comparator<? super K> cmp) {
16 @SuppressWarnings("unchecked")
17 private V val(int i) {return((V)vbuf[i]);}
18 @SuppressWarnings("unchecked")
19 private K key(int i) {return((K)kbuf[i]);}
21 private void raise(V val, K key, int i) {
23 int p = (i - 1) >>> 1;
24 if(cmp.compare(key(p), key) <= 0)
36 private void lower(V val, K key, int i) {
38 int c1 = (i << 1) + 1, c2 = c1 + 1;
41 int c = ((c2 < size) && (cmp.compare(key(c1), key(c2)) > 0)) ? c2 : c1;
42 if(cmp.compare(key(c), key) > 0)
54 private void adjust(V val, K key, int i) {
55 if((i > 0) && cmp.compare(key((i - 1) >> 1), key) > 0)
66 return((size > 0) ? val(0) : null);
80 throw(new NoSuchElementException());
88 return((size > 0) ? key(0) : null);
91 public void add(V val, K key) {
92 if(index.containsKey(val))
93 throw(new IllegalStateException());
95 if(p >= vbuf.length) {
96 int n = Math.max(vbuf.length * 2, 16);
97 vbuf = Arrays.copyOf(vbuf, n);
98 kbuf = Arrays.copyOf(kbuf, n);
103 public K update(V val, K key) {
104 Integer p = index.get(val);
106 throw(new NoSuchElementException());
112 public K set(V val, K key) {
113 Integer p = index.get(val);
123 private K remove(int p) {
127 } else if(p < size) {
128 adjust(val(size), key(size), p);
130 throw(new AssertionError());
137 public K remove(V val) {
138 Integer p = index.remove(val);
144 public boolean contains(V val) {
145 return(index.containsKey(val));
148 public String toString() {
149 StringBuilder buf = new StringBuilder();
151 for(int i = 0; i < size; i++) {
154 buf.append(String.valueOf(kbuf[i]));
156 buf.append(String.valueOf(vbuf[i]));
159 return(buf.toString());