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 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
| package com;
public class IndexMinPriorityQueue<T extends Comparable<T>> {
private T[] data; private int[] pq; private int[] qp; private int indexMinPriorityQueueLength;
IndexMinPriorityQueue(int capacity) { this.data = (T[]) new Comparable[capacity+1]; this.pq = new int[capacity+1]; this.qp = new int[capacity+1]; this.indexMinPriorityQueueLength = 0;
for (int i = 0; i < qp.length; i++) { qp[i] = -1; } }
public int size() { return indexMinPriorityQueueLength; }
public boolean isEmpty() { return indexMinPriorityQueueLength==0; }
private boolean less(int i, int j) { return data[pq[i]].compareTo(data[pq[j]]) < 0; }
private void exch(int i, int j) { int tmp = pq[i]; pq[i] = pq[j]; pq[j] = tmp; qp[pq[i]] = i; qp[pq[j]] = j; }
private boolean contains(int k) { return qp[k]!=-1; }
public int minIndex() { return pq[1]; }
public void insert(int i, T t) { if (contains(i)) { return; } indexMinPriorityQueueLength++; data[i] = t; pq[indexMinPriorityQueueLength] = i; qp[i] = indexMinPriorityQueueLength; swim(indexMinPriorityQueueLength); }
public int delMin() { int minIndex = pq[1]; exch(1, indexMinPriorityQueueLength); qp[pq[indexMinPriorityQueueLength]] = -1; pq[indexMinPriorityQueueLength] = -1; data[minIndex] = null; indexMinPriorityQueueLength--; sink(1); return minIndex; }
public void delete(int i) { int k = qp[i];
exch(k, indexMinPriorityQueueLength); qp[pq[indexMinPriorityQueueLength]] = -1; pq[indexMinPriorityQueueLength] = -1; data[indexMinPriorityQueueLength] = null; indexMinPriorityQueueLength--; sink(k); swim(k); }
public void changeItem(int i, T t) { data[i] = t; int k = qp[i]; sink(k); swim(k); }
private void swim(int k) { while (k>1) { if (less(k, k/2)) { exch(k, k/2); } k = k/2; } }
private void sink(int k) { while (2*k<=indexMinPriorityQueueLength) { int min; if (2*k+1<=indexMinPriorityQueueLength) { if (less(2*k, 2*k+1)) { min = 2*k; } else { min = 2*k+1; } } else { min = 2*k; } if (less(k, min)) { break; } exch(k, min); k = min; } }
}
|