Cod sursa(job #3156109)

Utilizator Paul281881818818181991919191881818Draghici Paul Paul281881818818181991919191881818 Data 10 octombrie 2023 16:53:25
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.08 kb
#include <fstream>
#include <vector>
#include <climits>
#include <iostream>
#define left(n) 2 * n
#define right(n) 2 * n + 1
#define N 200001
std::ifstream fin("heapuri.in");
std::ofstream fout("heapuri.out");
std::vector<int> List; int k = 1;
int elem[N], posarb[N];
void add(int value, std::vector<int>& List){
    List[k++] = value;
    posarb[value] = k - 1;
    int x = k - 1;
    while(x != 1 && elem[List[x]] < elem[List[x / 2]]){
        std::swap(posarb[List[x]], posarb[List[x / 2]]);
        std::swap(List[x], List[x / 2]);
        x /= 2;
    }
}

void heapify(int node, std::vector<int>& List){
    int i = node, mn = elem[List[node]];
    if(left(node) < k && elem[List[left(node)]] < mn){
        mn = elem[ List[ left(node) ] ]; i = left(node);
    }
    if(right(node) < k && elem[List[right(node)]] < mn){
        mn = elem[List[right(node)]]; i = right(node);
    }
    if(i != node){
        std::swap(posarb[List[node]], posarb[List[i]]);
        std::swap(List[node], List[i]);
        heapify(i, List);
    }
}
void heapifyutil(int node, std::vector<int> &List){
    posarb[List[k - 1]] = posarb[List[node]];
    List[node] = List[k - 1];
    //elem[List[node]] = elem[List[k - 1]];
    k-- ;
    heapify(node, List);
}
void del(int node, std::vector<int>& List){
    elem[List[node]] = INT_MIN;
    while(node != 1 && elem[List[node]] < elem[List[node / 2]]){
        std::swap(posarb[List[node]], posarb[List[node / 2]]);
        std::swap(List[node], List[node / 2]);
        node /= 2;
    }
    heapifyutil(1, List);
}
int main(){
    int n;
    fin >> n;
    int op, x, cnt = 0;
    List = std::vector<int> (4 * n);
    for(int i = 1; i <= n; i++){
        fin >> op;
        if(op == 1){
            fin >> x;
            elem[++cnt] = x;
            add(cnt, List);
        }
        else if(op == 2){
            fin >> x;
            del(posarb[x], List);
        }
        else{
            fout << elem[List[1]] << "\n";
        }
    }
    for(int i = 1; i <= cnt; i++)
        std::cout << List[posarb[i]] << " ";
}