Pagini recente » Cod sursa (job #1367046) | Cod sursa (job #111852) | Cod sursa (job #1452364) | Cod sursa (job #721868) | Cod sursa (job #1489106)
import java.io.*;
import java.util.*;
public class Main {
private static Scanner scanner;
private static BufferedWriter bufferedWriter;
private static List<Integer> heap = new ArrayList<>();
private static HashMap<Integer, Integer> indexValueMap = new HashMap<>();
private static HashMap<Integer, Integer> heapIndex = new HashMap<>();
public static void main(String args[]) throws IOException {
scanner = new Scanner(new FileInputStream("heapuri.in"));
bufferedWriter = new BufferedWriter(new FileWriter("heapuri.out"));
heap.add(0);
int type, n = scanner.nextInt();
for (int i = 1; i <= n; ++i) {
type = scanner.nextInt();
switch (type) {
case 1:
int x = scanner.nextInt();
indexValueMap.put(heap.size(), x);
heapIndex.put(heap.size(), heap.size());
insert(heap.size());
break;
case 2:
int index = scanner.nextInt();
remove(heapIndex.get(index));
break;
case 3:
bufferedWriter.write("" + indexValueMap.get(heap.get(1)));
bufferedWriter.newLine();
}
}
scanner.close();
bufferedWriter.close();
}
private static int insert(Integer index) {
heap.add(index);
int currentIndex = heap.size() - 1;
while (currentIndex > 1) {
int parentIndex = currentIndex >> 1;
int currentHeapValue = heap.get(currentIndex);
int parentHeapValue = heap.get(parentIndex);
if (indexValueMap.get(currentHeapValue) < indexValueMap.get(parentHeapValue)) {
swapHeapIndex(currentHeapValue, parentHeapValue);
Collections.swap(heap, currentIndex, parentIndex);
currentIndex = parentIndex;
} else {
break;
}
}
return currentIndex;
}
private static void remove(int index) {
heap.set(index, heap.get(heap.size() - 1));
heap.remove(heap.size() - 1);
int currentIndex = 1;
while (currentIndex * 2 < heap.size()) {
int smallestChildIndex = getSmallestChildIndex(currentIndex);
int currentHeapValue = heap.get(currentIndex);
int smallestChildHeapValue = heap.get(smallestChildIndex);
if (indexValueMap.get(currentHeapValue) > indexValueMap.get(smallestChildHeapValue)) {
swapHeapIndex(currentHeapValue, smallestChildHeapValue);
Collections.swap(heap, currentIndex, smallestChildIndex);
} else {
break;
}
}
}
private static void swapHeapIndex(int currentHeapValue, int parentHeapValue) {
int currentHeapIndex = heapIndex.get(currentHeapValue);
int parentHeapIndex = heapIndex.get(parentHeapValue);
heapIndex.put(currentHeapValue, parentHeapIndex);
heapIndex.put(parentHeapValue, currentHeapIndex);
}
private static int getSmallestChildIndex(int currentPosition) {
int smallestChildIndex = currentPosition << 1;
if (smallestChildIndex + 1 < heap.size() &&
indexValueMap.get(heap.get(smallestChildIndex)) > indexValueMap.get(heap.get(smallestChildIndex + 1))) {
smallestChildIndex++;
}
return smallestChildIndex;
}
}