Cod sursa(job #2893150)

Utilizator iulia.talpalariuIulia-Georgiana Talpalariu iulia.talpalariu Data 25 aprilie 2022 12:45:19
Problema Heapuri Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.43 kb
#include <fstream>

int v[200003];
int heap[200003]; // heapul va avea pozitiile din v
int poz[200003];
int m = 0; // pozitiile pe care sunt introduse elemente
int k = 0; // pozitia pe care adaug acuma element
/*
void afisare() {
    std::cout << "Elementele din v sunt :";
    for ( int i=1; i <= m; i++) {
        std::cout << i<< " .";
        std::cout << v[i]<<"\n";



    }
    std::cout << "Elementele din heap sunt :";
    for ( int i=1; i <= k; i++) {
        std::cout << i<< " .";
        std::cout << v[heap[i]]<<"\n";



    }
}
*/

void heapify(int s, int i)
{
    int minim = i; // Initialize largest as root
    int st = 2 * i ; //
    int dr = 2 * i + 1; //

    // If left child is smaller than root
    if (st <= s && v[heap[st]] < v[heap[minim]])
        minim = st;

    // If right child is smaller than min so far
    if (dr <= s && v[heap[dr]] < v[heap[minim]])
        minim = dr;

    // If min is not root
    if (minim != i) {
        std::swap(heap[i], heap[minim]);
        poz[heap[i]] = i;
        poz[heap[minim]] = minim;
        heapify(s, minim);
    }
}

int main() {
int n, operatie;
int x;


    std::ifstream fileIn("heapuri.in");
    std::ofstream fileOut("heapuri.out");

    fileIn >> n; //nr operatii citite in continuare;

    for ( int i = 0; i < n; i++ ) {
        fileIn >> operatie;
        switch (operatie) {
        case 1 :{
        fileIn >> x;
        //std::cout <<"Introduceti "<< x <<" in heap\n";
        m++;
        k++;
        v[m] = x;
        heap[k] = m;
        poz[m] = k;

        int t = k;
        int aux;
        //tb sa urc elem
        while (t/2 && v[heap[t]]<v[heap[t/2]])
        {
            aux = heap[t];
            heap[t] = heap[t/2];
            heap[t/2] = aux;
            poz[heap[t]] = t;
            poz[heap[t/2]] = t/2;

            t /= 2;
        }

        break;
        }
        case 2:{
        fileIn >> x;
        //std::cout <<"Eliminati al x-lea introdus "<< v[x] <<" din heap\n";
        std::swap(heap[poz[x]],heap[k]);
        poz[heap[k]] = poz[x];
        k--;
        heapify(k,1);
        break;
        }
        case 3: {
        //std::cout <<"Afiseaza "<< v[heap[1]] <<" care e root of the heap\n";
        //afisare();
        fileOut << v[heap[1]]<<"\n";
        break;
        }
        default:
            break;
        }

    }



    return 0;

}