Cod sursa(job #2002198)

Utilizator andreisontea01Andrei Sontea andreisontea01 Data 18 iulie 2017 23:27:45
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.72 kb
//
//  main.cpp
//  heap-sort
//
//  Created by Andrei Sontea on 09/07/17.
//  Copyright © 2017 Andrei Sontea. All rights reserved.
//

#include <cstdio>
#include <vector>
//#include <algorithm>

using namespace std;

vector<int> vals, poses, heap;

int n, size_heap, size_insert;


void swap(int p1, int p2){
    int aux = heap[p1];
    heap[p1] = heap[p2];
    heap[p2] = aux;
    aux = poses[heap[p1]];
    poses[heap[p1]] = poses[heap[p2]];
    poses[heap[p2]] = aux;
}

void heap_sus(int p){
    if(p == 1)
        return;
    if(vals[heap[p]] < vals[heap[p / 2]]){
        swap(p, p / 2);
        heap_sus(p / 2);
    }
}


void heap_jos(int p){
    int new_p = 0;
    if(2 * p <= size_heap && vals[heap[p]] > vals[heap[2 * p]])
        new_p = 2 * p;
    if((2 * p + 1 <= size_heap && vals[heap[2 * p + 1]] < vals[heap[2 * p]]) && vals[heap[p]] > vals[heap[2 * p + 1]])
        new_p = 2 * p + 1;
    if(new_p != 0){
        swap(p, new_p);
        heap_jos(new_p);
    }
}

void insert(int news){
    size_insert++;
    int last = size_insert;
    vals.push_back(news);
    heap.push_back(last);
    size_heap++;
    poses[last] = size_heap;
    heap_sus(poses[last]);
}

void sterg(int pos){
    swap(poses[pos], size_heap);
    size_heap--;
    heap.pop_back();
    heap_sus(pos);
    heap_jos(pos);
}


int main(){
    scanf("%d", &n);
    int command, new_el, pos;
    vals.push_back(0);
    heap.push_back(0);
    for(int i = 1;i <= n;i++){
        scanf("%d", &command);
        if(command == 1){
             scanf("%d", &new_el);
            insert(new_el);
        }
        else if(command == 2){
             scanf("%d", &pos);
            sterg(pos);
        }
        else
            printf("%d\n", vals[heap[1]]);
    }
    return 0;
}