Cod sursa(job #2593909)

Utilizator circeanubogdanCirceanu Bogdan circeanubogdan Data 4 aprilie 2020 20:56:08
Problema Heapuri Scor 100
Compilator c-64 Status done
Runda Arhiva educationala Marime 1.86 kb
#include <stdio.h>
#include <stdlib.h>
#define DIM 200010

int noTests, type, nHeap, nInput, x;
int heap[DIM];
int pos[DIM];
int values[DIM];

int getMax(){
    return values[heap[1]];
}

void swapNodes(int a, int b){
    int aux;
    aux = heap[a];
    heap[a] = heap[b];
    heap[b] = aux;
    pos[heap[a]] = a;
    pos[heap[b]] = b;
}

void sift(int node){
    int left = 2 * node;
    int right = 2 * node + 1;
    int minNode = node;
    if(left <= nHeap && values[heap[left]] < values[heap[minNode]])
        minNode = left;
    if(right <= nHeap && values[heap[right]] < values[heap[minNode]])
        minNode = right;
    swapNodes(node, minNode);
    if(node != minNode)
        sift(minNode);
}

int percolate(int node){
    while(node > 1){
        int father = node / 2;
        if(values[heap[father]] > values[heap[node]]){
            swapNodes(node, father);
            node = father;
        }
        else{
            break;
        }
    }
    return node;
}

int main()
{
    FILE *in = fopen("heapuri.in", "r");
    FILE *out = fopen("heapuri.out", "w");

    fscanf(in, "%d", &noTests);

    for(int crtTest = 1; crtTest <= noTests; ++ crtTest){
        fscanf(in, "%d", &type);
        switch(type){
            case 1:
                fscanf(in, "%d", &values[++nInput]);
                pos[nInput] = ++nHeap;
                heap[nHeap] = nInput;
                percolate(nHeap);
                break;
            case 2:
                fscanf(in, "%d", &x);
                int position = pos[x];
                swapNodes(pos[x], nHeap);
                nHeap --;
                position = percolate(position);
                sift(position);
                break;
            case 3:
                fprintf(out, "%d\n", getMax());
                break;
        }
    }

    return 0;
}