Mai intai trebuie sa te autentifici.

Cod sursa(job #2893121)

Utilizator iulia.talpalariuIulia-Georgiana Talpalariu iulia.talpalariu Data 25 aprilie 2022 12:11:50
Problema Heapuri Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.29 kb
#include <iostream>
#include <fstream>

int *v = new int(200001);
int *heap = new int(200001); // heapul va avea pozitiile din v
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 n, 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 <= n && v[heap[st]] < v[heap[minim]])
        minim = st;

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

    // If min is not root
    if (minim != i) {
        std::swap(heap[i], heap[minim]);
        heapify(n, 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;
        heapify(k,1);
        break;
        }
        case 2:{
        fileIn >> x;
        //std::cout <<"Eliminati al x-lea introdus "<< v[x] <<" din heap\n";
        for(int p = 1; p<=k; p++) {
            if (heap[p] == x) {
                std::swap(heap[p],heap[k]);
                //std::cout << v[heap[p]]<<" "<< v[heap[k]]<<"\n";
                k--;
                heapify(k,1);
                break;
            }
        }
        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;
        }

    }


    delete [] v;
    delete [] heap;
    return 0;

}