1 package org.matsim.core.router.speedy;
3 import java.util.NoSuchElementException;
29 private final int[] heap;
30 private final int[] pos;
33 private final double[] cost;
35 DAryMinHeap(
int nodeCount,
int d) {
36 this.heap =
new int[nodeCount];
37 this.pos =
new int[nodeCount];
38 this.cost =
new double[nodeCount];
42 void insert(
int node,
double cost) {
47 int parent = parent(i);
48 while (i > 0 && cost < this.cost[parent]) {
49 this.heap[i] = this.heap[parent];
50 this.pos[this.heap[parent]] = i;
51 this.cost[i] = this.cost[parent];
53 parent = parent(parent);
60 void decreaseKey(
int node,
double cost) {
61 int i = this.pos[node];
69 if (this.heap[i] != node) {
70 throw new NoSuchElementException(
"The element with index " + i +
" could not be found at the proper location in the heap.");
72 if (this.cost[i] < cost) {
73 throw new IllegalArgumentException(
"existing cost is already smaller than new cost.");
77 int parent = parent(i);
78 while (i > 0 && cost < this.cost[parent]) {
79 this.heap[i] = this.heap[parent];
80 this.cost[i] = this.cost[parent];
81 this.pos[this.heap[parent]] = i;
83 parent = parent(parent);
92 throw new NoSuchElementException(
"heap is empty");
99 int root = this.heap[0];
107 if (this.size == 0) {
108 throw new NoSuchElementException(
"heap is empty");
113 public boolean remove(
int node) {
114 int i = this.pos[node];
128 return this.size == 0;
135 private void fixWhole(
int index) {
138 int left = left(index);
139 if (left >= this.size) {
142 int right = right(index);
143 if (right >= this.size) {
144 right = this.size - 1;
148 double smallestCost = this.cost[left];
149 for (
int child = left + 1; child <= right; child++) {
150 double childCost = this.cost[child];
151 if (childCost <= smallestCost) {
152 if (childCost < smallestCost || this.heap[child] < this.heap[smallest]) {
154 smallestCost = childCost;
159 this.heap[index] = this.heap[smallest];
160 this.cost[index] = smallestCost;
161 this.pos[this.heap[index]] = index;
168 if (index < this.size) {
169 this.heap[index] = this.heap[this.size];
170 this.cost[index] = this.cost[this.size];
171 this.pos[this.heap[index]] = index;
175 double nodeCost = this.cost[index];
177 int parent = parent(index);
178 double parentCost = this.cost[parent];
179 if (nodeCost < parentCost) {
188 private int right(
int i) {
189 return this.d * i + this.d;
192 private int left(
int i) {
193 return this.d * i + 1;
196 private int parent(
int i) {
197 return (i - 1) / this.d;
200 private void swap(
int i,
int parent) {
201 int tmp = this.heap[parent];
202 this.heap[parent] = this.heap[i];
203 this.pos[this.heap[i]] = parent;
207 double tmpC = this.cost[parent];
208 this.cost[parent] = this.cost[i];
212 public IntIterator iterator() {
213 return new HeapIntIterator();
226 return this.pos > DAryMinHeap.this.size;
231 int node = DAryMinHeap.this.heap[this.pos];