Pagini recente » Cod sursa (job #1347772) | Cod sursa (job #416892) | Cod sursa (job #1746105) | Cod sursa (job #935369) | Cod sursa (job #2683692)
import java.io.*;
import java.util.HashMap;
import java.util.Scanner;
public class Main {
private static int n;
private static int [] heap; // contains values and we know how to traverse it
private static int size;
private static int [] orderOfInsertion; // knows the order of insertion and has values
private static HashMap<Integer, Integer> knowsTheIndexOfValue;
private static int currentElementInserted = 1;
public static void main(String []args) {
File inputFile = new File("heapuri.in");
File outputFile = new File("heapuri.out");
try {
FileInputStream inputStream = new FileInputStream(inputFile);
Scanner scanner = new Scanner(inputStream);
FileOutputStream outputStream = new FileOutputStream(outputFile);
PrintWriter writer = new PrintWriter(outputStream);
n = scanner.nextInt(); // the number of commands
heap = new int[n + 1]; // if all inserts we cannot have more than this
knowsTheIndexOfValue = new HashMap<>();
orderOfInsertion = new int[n + 1];
int command;
int number;
for (int i = 0; i < n; i++) {
command = scanner.nextInt();
if (command == 3) {
writer.println(heap[1]);
continue;
}
number = scanner.nextInt();
if (command == 1)
insert(number);
if (command == 2)
delete(number);
}
writer.close();
outputStream.close();
} catch(IOException e) {
}
}
private static void insert(int number) {
heap[size + 1] = number;
int positionToBeDeleted = size + 1;
knowsTheIndexOfValue.put(number, size + 1);
orderOfInsertion[currentElementInserted] = number;
size++;
while (positionToBeDeleted > 0 && heap[positionToBeDeleted / 2] > heap[positionToBeDeleted]) {
swap(positionToBeDeleted, positionToBeDeleted / 2);
positionToBeDeleted = positionToBeDeleted / 2;
}
currentElementInserted++;
}
private static void delete(int number) {
int valToBeDeleted = orderOfInsertion[number];
int positionToBeDeleted = knowsTheIndexOfValue.get(valToBeDeleted);
swap(positionToBeDeleted, size);
heap[size] = 0;
size--;
while (heap[positionToBeDeleted / 2] > heap[positionToBeDeleted]) {
swap(positionToBeDeleted, positionToBeDeleted / 2);
positionToBeDeleted = positionToBeDeleted / 2;
}
while (2 * positionToBeDeleted <= size){
int minKidPoisition = 2 * positionToBeDeleted;
if (2 * positionToBeDeleted + 1 <= size)
if (heap[minKidPoisition] > heap[2 * positionToBeDeleted + 1])
minKidPoisition = 2 * positionToBeDeleted + 1;
if (heap[minKidPoisition] < heap[positionToBeDeleted]){
swap(positionToBeDeleted, minKidPoisition);
positionToBeDeleted = minKidPoisition;
}
}
}
private static void swap(int firstPosition, int secondPosition)
{
int tmp = heap[firstPosition];
heap[firstPosition] = heap[secondPosition];
heap[secondPosition] = tmp;
// Because we swapped them already!
knowsTheIndexOfValue.put(heap[firstPosition], firstPosition);
knowsTheIndexOfValue.put(tmp, secondPosition);
}
}