-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathE2433.java
145 lines (119 loc) · 2.69 KB
/
E2433.java
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
import edu.princeton.cs.algs4.StdOut;
import java.util.Arrays;
/**
* Compilation: javac E2433.java
* Execution: java E2433
*
* $ java E2433
* [null, L, P, M, Q, P, X, null]
*/
/**
* E2433
*/
public class E2433 {
private static class IndexMinPQ<Key extends Comparable<Key>> {
private Key[] keys;
private int[] pq;
private int[] inverse;
private int n;
public IndexMinPQ(int max) {
keys = (Key[]) new Comparable[max + 1];
pq = new int[max + 1];
inverse = new int[max + 1];
for (int i = 0; i <= max; i++) {
inverse[i] = -1;
}
}
public void insert(int i, Key key) {
n++;
pq[n] = i;
inverse[i] = n;
keys[i] = key;
swim(n);
}
/**
* Exercise 2.4.33
*/
public boolean contains(int i) {
return inverse[i] != -1;
}
public Key minKey() {
return keys[pq[1]];
}
public int delMin() {
int min = pq[1];
exchange(1, n--);
sink(1);
inverse[pq[n + 1]] = -1;
keys[pq[n + 1]] = null;
return min;
}
public boolean isEmpty() {
return n == 0;
}
public int size() {
return n;
}
public Key keyOf(int i) {
return keys[pq[i]];
}
/**
* Exercise 2.4.33
*/
private boolean greater(int i, int j) {
return keyOf(i).compareTo(keyOf(j)) > 0;
}
/**
* Exercise 2.4.33
*/
private void exchange(int i, int j) {
int ti = pq[i];
int tj = pq[j];
pq[i] = tj;
pq[j] = ti;
int t = inverse[ti];
inverse[ti] = inverse[tj];
inverse[tj] = t;
}
private void swim(int k) {
while (k > 1 && greater(k / 2, k)) {
exchange(k / 2, k);
k = k / 2;
}
}
private void sink(int k) {
while (2 * k <= size()) {
int j = 2 * k;
if (j < n && greater(j, j + 1)) {
j++;
}
if (!greater(k, j)) {
break;
}
exchange(k, j);
k = j;
}
}
public String toString() {
Key[] pqKeys = (Key[]) new Comparable[keys.length];
for (int i = 1; i <= n; i++) {
pqKeys[i] = keyOf(i);
}
return Arrays.toString(pqKeys);
}
}
public static void main(String[] args) {
IndexMinPQ<String> queue = new IndexMinPQ<String>(7);
queue.insert(queue.size(), "P");
queue.insert(queue.size(), "Q");
queue.insert(queue.size(), "E");
queue.insert(queue.delMin(), "X");
queue.insert(queue.size(), "A");
queue.insert(queue.size(), "M");
queue.insert(queue.delMin(), "P");
queue.insert(queue.size(), "L");
queue.insert(queue.size(), "E");
queue.delMin();
StdOut.println(queue);
}
}